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