var fruits = ["Banana", "Orange", "Apple", "Mango"];
1.indexOf:
开始检索的位置在数组 start 处或数组的开头(没有指定 start 参数时)。如果找到一个 item,则返回 item 的第一次出现的位置,如果没找到指定元素则返回 -1。(indexOf值如果>=0则是找到,-1则是没有找到
)
2.includes:
fruits.includes('Orange')//true
includes() 方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false。
另外还可以再接受一个索引值 例如fruits.includes('Orange', index)
如果为负,则按升序从 fruits.length + index的索引开始搜索。默认为 0。
如果index大于等于数组长度则返回 false 。该数组不会被搜索。
如果 index 为负值,计算出的索引将作为开始搜索'Orange'的位置。如果计算出的索引小于 0,则整个数组都会被搜索。
3.find:
fruits.find((item)=>item==='Orange')//Orange
同时可以传递更多的参数
fruits.find(function (currentValue, index, arr) {
},thisValue)
currentValue:当前元素
index:索引
arr:当前元素所属的数组对象
thisValue:传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值
返回符合条件的第一个数组元素值,如果没有符合条件的则返回 undefined。
4.filter
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。filter() 不会对空数组进行检测。 filter() 不会改变原始数组。
fruits.filter(function (currentValue, index, arr) {
},thisValue)
参数和find一样
返回数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
fruits.filter((item)=>item==='Orange')//["Orange"]
5.forEach
forEach() 对于空数组是不会执行回调函数的。
array.forEach(function(currentValue, index, arr), thisValue)
fruits.forEach((item)=>{
if(item==='Orange'){
item='ss';
}
})
console.log(fruits)//["Banana", "Orange", "Apple", "Mango"]
在forEach中修改item值时数组并不会改变
如果想要修改则:
fruits.forEach((item,index)=>{
if(item==='Orange'){
fruits[index]='ss'
}
})
console.log(fruits)// ["Banana", "ss", "Apple", "Mango"]
6.map:
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
array.map(function(currentValue,index,arr), thisValue)
var newArr=fruits.map((item,index)=>{
if(item==='Orange'){
return item
}
})
console.log(newArr)//[undefined, "Orange", undefined, undefined]
7.reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
total 必需。初始值, 或者计算结束后的返回值。
currentValue 必需。当前元素
currentIndex 可选。当前元素的索引
arr 可选。当前元素所属的数组对象。
var items = [10, 120, 1000];
// our reducer function
var reducer = function add(sumSoFar, item) { return sumSoFar + item; };
// do the job
var total = items.reduce(reducer, 0);
console.log(total); // 1130
var items = [10, 120, 1000];
// our reducer function
var reducer = function add(sumSoFar, item) {
sumSoFar.sum = sumSoFar.sum + item;
return sumSoFar;
};
// do the job
var total = items.reduce(reducer, {sum: 0});
console.log(total); // {sum:1130}
for in和for of 单独记录