arr.reduce(callback(accumulator, currentValue), initialValue)
- callback是回调函数
- initialValue是accumulator累加器的初始值
- currentValue代表当前你所遍历到的数组中的元素值
- 每一次的accumulator都是上一次callback的返回值
例子如下
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15