1.forEach
forEach是ECMA5中Array新方法中最基本的一个,就是遍历,循环。例如下面这个例子:
- [1, 2 ,3, 4].forEach(alert); 等同于下面这个for循环
var array = [1, 2, 3, 4];
for (var k = 0, length = array.length; k < length; k++) {
alert(array[k]);
}
Array在ES5新增的方法中,参数都是function类型,默认有传参,forEach方法中的function回调支持3个参数,第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身。 因此,我们有:
[].forEach(function(value, index, array) {
// ...
});
2.map
这里的map不是“地图”的意思,而是指“映射”。[].map(); 基本用法跟forEach方法类似: array.map(callback,[ thisObject]); callback的参数也类似:
[].map(function(value, index, array) {
// ...
});
map方法的作用不难理解,“射就是原数组被“映射”成对应新数组。下面这个例子是数值项求平方:
var data=[1,3,4]
var Squares=data.map(function(val,index,arr){
console.log(arr[index]==val); // ==> true
return val*val
})
console.log(Squares); // ==> [1, 9, 16]
注意:由于forEach、map都是ECMA5新增数组的方法,所以ie9以下的浏览器还不支持,可以从Array原型扩展可以实现以上全部功能,例如forEach方法:
if (typeof Array.prototype.forEach != "function") {
Array.prototype.forEach = function() {
/* 实现 */
};
}
3.filter
经过filter函数后会创建一个新的数组, 回调函数返回的结果一个boolean值,若结果为真,则返回匹配的项,若为假,则返回一个空数组,它不会改变原有数组,返回的是过滤后的新数组
Array.filter(function(currentVal,index,arrs){
// do something
}
4.find
返回通过测试(函数内判断)的数组的第一个元素的值。
- 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
- 如果没有符合条件的元素返回 undefined
5.every
是对数组中每一项运行给定函数,如果该函数对每一项返回true,则返回true。如果数组没有元素,则 every() 方法将返回 true。
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.every( function( item, index, array ){
console.log( 'item=' + item + ',index='+index+',array='+array );
return item > 3;
})); // false
6.some
是对数组中每一项运行给定函数,如果该函数对任一项返回true,则返回true
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.some( function( item, index, array ){
console.log( 'item=' + item + ',index='+index+',array='+array );
return item > 3;
})); // true
7.reduce
reduce(callback(total,item,index,arr),initial)方法有两个参数,第一个参数是一个回调函数(必须),第二个参数是初始值(可选)。数组将上一次的返回值作为下一次循环的初始值,最后将这个结果返回。如果没有初始值,则reduce会将数组的第一个元素作为循环开始的初始值。
total: 累计值; item: 当前循环的元素(必须); inedx: 该元素的索引(可选); arr:数组本身(可选) 常用于数组元素的累加、累乘。(reduce方法不改变原数组)
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const sum = arr.reduce((total, value, index) => {
console.log(total);
return total + value
}, 100)
console.log('sum=' + sum); // sum=145
let arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const sum_2 = arr2.reduce((total_2, value, index) => {
console.log(total_2);
return total_2 + value
})
console.log('sum_2=' + sum_2); // sum_2=45