reduce()
方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。
arr.reduce([callback, initialValue])
callback
执行数组中每个值的函数,包含四个参数:
previousValue
上一次调用回调函数返回的值,或者是提供的初始值(initialValue)
currentValue
数组中当前被处理的元素
currentIndex
当前被处理元素在数组中的索引, 即currentValue的索引.如果有initialValue初始值, 从0开始.如果没有从1开始.
array
调用 reduce 的数组
initialValue
可选参数, 作为第一次调用 callback 的第一个参数。
返回值
最后一次调用回调函数返回的结果
reduce是如何工作的
例如执行下面的代码
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
回调被执行四次,每次的参数和返回值如下表:
previousValue currentValue index array return value
first call 0 1 1 [0,1,2,3,4] 1
second call 1 2 2 [0,1,2,3,4] 3
third call 3 3 3 [0,1,2,3,4] 6
fourth call 6 4 4 [0,1,2,3,4] 10
reduce
的返回值是回调函数最后一次被调用的返回值(10)。
用箭头函数也可以的
[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr );
如果把初始值作为第二个参数传入 reduce
,结果如下,结果如下:
[0,1,2,3,4].reduce( (previousValue, currentValue, currentIndex, array) => {
return previousValue + currentValue;
}, 10);
previousValue currentValue index array return value
first call 10 0 0 [0,1,2,3,4] 10
second call 10 1 1 [0,1,2,3,4] 11
third call 11 2 2 [0,1,2,3,4] 13
fourth call 13 3 3 [0,1,2,3,4] 16
fifth call 16 4 4 [0,1,2,3,4] 20
最后一次函数调用的返回值 (20) 作为reduce函数的结果被返回.
例题
将数组所有项相加
var total = [0, 1, 2, 3].reduce(function(a, b) {
return a + b;
}, 0);
// total == 6
或者用箭头函数这样写:
var total = [ 0, 1, 2, 3 ].reduce( ( acc, cur ) => acc + cur, 0 );
扁平化一个二维数组
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]
兼容旧环境(Polyfill)
Array.prototype.reduce 被添加到 ECMA-262 标准第 5 版;因此可能在某些实现环境中不被支持。可以将下面的代码插入到脚本开头来允许在那些未能原生支持 reduce 的实现环境中使用它。
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(callback /*, initialValue*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
var t = Object(this), len = t.length >>> 0, k = 0, value;
if (arguments.length == 2) {
value = arguments[1];
} else {
while (k < len && !(k in t)) {
k++;
}
if (k >= len) {
throw new TypeError('Reduce of empty array with no initial value');
}
value = t[k++];
}
for (; k < len; k++) {
if (k in t) {
value = callback(value, t[k], k, t);
}
}
return value;
};
}