// 将a中的数字累加
let a = [1, 2, 3, 4, 5]
// reduce(acc,cur,idx,src) acc累积器 cur当前值 idx当前索引 src原数组 idx,src可选
let a1 = a.reduce((acc, cur) => acc + cur)
console.log(a1); // a1=15 1+2+3+4+5
// 将b中的对象 合并成{1: "男", 2: "nv"}
let b = [{
id: 1,
value: '男'
},
{
id: 2,
value: 'nv'
}
]
let b1 = b.reduce((acc, cur) => {
let c = cur.id
let c1 = cur.value
acc[c] = c1
return acc
}, {}) //
console.log(b1); // {1: "男", 2: "nv"}
reduce
为数组中的每一个元素依次执行callback
函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:
accumulator 累计器
currentValue 当前值
currentIndex 当前索引
array 数组
回调函数第一次执行时,accumulator
和currentValue
的取值有两种情况:如果调用reduce()
时提供了initialValue
,accumulator
取值为initialValue
,currentValue
取数组中的第一个值;如果没有提供 initialValue
,那么accumulator
取数组中的第一个值,currentValue
取数组中的第二个值。