reduce方法对数组中的每个元素执行一次reduce函数,将其结果汇总为单个返回值。
语法
arr.reduce(callback(accumulator, currentValue[, index[, array]])[,initValue])
// 参数
callback:执行数组中每个值(如果没有提供initValue,则第一个值除外)的函数,包含四个参数。
accumnlator:累计器累计回调的返回值,它是上一次调用回调时累计的返回值,或initValue。
currentValue:正在处理的数组元素。
index:(可选)正在处理的数组元素的索引。如果提供了initValue则起始索引为0,否则从索引1开始。
array:(可选)调用reduce回调函数的数组。
initValue:作为第一次调用callback回调函数第一个参数的值。如果没有提供初始值,则使用数组中第一个元素的值。在没有提供初始值的空数组上调用reduce将报错。
// 返回值
回调函数累计处理的结果。
描述
reduce为数组中每个元素依次执行callback回调函数,不包括数组中已删除或从未赋值的元素,接受四个参数
- accumulator:累计器
- currentValue:当前值
- index:当前值的索引
- array:调用reduce的数组
函数第一次执行时,accumulator和currentValue的取值有两种情况:如果调用reduce提供了initValue,accumulator取值为initValue,currentValue取值为数组的第一个元素。如果没有提供initValue,accumulator取值为数组的第一个元素,currentValue取值为数组的第二个元素。
如果没有提供initValue,reduce会从索引为1的位置开始执行函数,跳过第一个索引。如果提供了initValue,则从索引0开始。
reduce如何运行
假如运行一下代码
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, index, array) {
return accumulator + currentValue;
})
callback 被调用四次,每次调用的参数和返回值如下表
callback | accumulator | currentValue | index | array | return value |
---|---|---|---|---|---|
1 | 1 | 1 | [0, 1, 2, 3, 4] | 1 | |
2 | 1 | 2 | 2 | [0, 1, 2, 3, 4] | 3 |
3 | 3 | 3 | 3 | [0, 1, 2, 3, 4] | 6 |
4 | 6 | 4 | 4 | [0, 1, 2, 3, 4] | 10 |
如果提供一个初始值作为reduce的第二个参数,则每次调用的参数和返回值如下
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, index, array) {
return accumulator + currentValue;
}, 10)
callback | accumulator | currentValue | index | array | return value |
---|---|---|---|---|---|
1 | 10 | [0, 1, 2, 3, 4] | 10 | ||
2 | 10 | 1 | 1 | [0, 1, 2, 3, 4] | 11 |
3 | 11 | 2 | 2 | [0, 1, 2, 3, 4] | 13 |
4 | 13 | 3 | 3 | [0, 1, 2, 3, 4] | 16 |
5 | 16 | 4 | 4 | [0, 1, 2, 3, 4] | 20 |
例子
数组里所有值的和
const sum = [1, 2, 3, 4].reduce((acc, cur) => acc + cur);
console.log(sum); // 10
累加对象数组中的值
// 要累加对象数组中的值,必须提供一个初始值,以便数组中每个元素可以顺利通过回调函数
const sum = [{x: 1}, {x: 2}, {x: 3}, {x: 4}].reduce((acc, cur) => {
return acc + cur.x;
}, 10);
console.log(sum); // 20