美文网首页
reduce()方法

reduce()方法

作者: 何小鹏 | 来源:发表于2021-03-17 10:39 被阅读0次
arr.reduce(callback(accumulator, currentValue, index, array), initialValue)

参数
callback (执行数组中每个值的函数,包含四个参数)

1、previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
2、currentValue (数组中当前被处理的元素)
3、index (当前元素在数组中的索引)
4、array (调用 reduce 的数组)

initialValue (作为第一次调用 callback 的第一个参数。)

使用
回调函数第一次执行时,accumulator 和currentValue的取值有两种情况:如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。

注意:如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。

const  arr = [1, 2, 3, 4];
const sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
},0) //注意这里设置了初始值
console.log(arr, sum);

打印结果:
0 1 0
1 2 1
3 3 2
6 4 3
[1, 2, 3, 4] 10

具体使用场景
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#%E8%AF%AD%E6%B3%95

相关文章

网友评论

      本文标题:reduce()方法

      本文链接:https://www.haomeiwen.com/subject/lkvkcltx.html