首页 > 代码库 > js的Array高阶函数常用方法forEach、map、reduce

js的Array高阶函数常用方法forEach、map、reduce

1.forEach方法用于调用数组的每一个元素,并将元素传递给回调函数。

array.forEach(function(currentValue,index,arr),thisValue);

1.currentValue 必须。当前元素。
2.index 可选。当前元素的索引值。
3.arr 可选。当前元素所对应的数组对象
4.thisValue 可选。传递给函数的值一般用this值,如果这个参数为空,“undefined”会传递给“this”值

2.map()方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

array.map(function(currentValue,index,arr),thisValue)

1.currentValue 必须,当前元素的值
2.index 可选。当前元素的索引值
3.arr 可选。当前元素所从属的数组对象
4.thisValue 可选。对象作为该执行回调时使用。传递给函数,用作”this“值。如果这个参数为空,“undefined”会传递给“this”值

3.reduce方法接收一个函数作为累加器,数组中的每个值开始缩减,最终计算为一个值

array.reduce(function(total,currentValue,currentIndex,arr),initialValue);
1.total 必须。初始值或计算结果后的返回值
2.currentValue 必须,当前元素。
3.currentIndex 可选。当前元素的索引
4.arr 可选。当前元素所属的数组对象
5.initialValue 可选。传递给函数的初始值

 

js的Array高阶函数常用方法forEach、map、reduce