- Array.prototype.reduce() 函数
函数将用户提供的 reducer 函数应用于数组所有元素,并将 reducer 函数最终返回值作为最终结果返回。
reducer 函数有四个参数,accumulator,currentValue,currentIndex,array, reducer 函数被 reduce 函数调用时,reduce 会将当前数据元素的值和索引赋值给 currentValue,currentIndex 以便在 reducer 函数内部使用。accumulator 变量是一个在reduce函数执行过程中全程可见的函数变量,reduce 函数支持为 accumulator 指定初始值 initialValue,如果 reduce 函数调用时没有指定初始值 initialValue,accumulator 将使用数组的第一个元素。array 为应用 reduce 函数的数组自身。
Array.reduce(function(accumulator,currentValue,currentIndex,array){}, initialValue)
在调用函数 reduce 时,reducer函数的位置参数 按照顺序依次被自动赋值为 上次callback时reducer函数的返回值,当前待处理的数组元素,当前待处理数组元素在数组中的索引,当前数组。也就是像这样:
function callback(a){} // a=accumulator, 其他忽略
function callback(a,b){} //a=accumulator, b=currentValue, 其他忽略
// 依此类推
起始时,accumulator 将被设置为数组第一个元素,currentValue 被设置为数组第二个元素,i.e. 回调函数首次调用是在数组的第二个元素上。如果设置了 initialValue,accumulator 将被值设为 initialValue,currentValue 被设置为数组第一个元素,回调函数首次调用发生在数组第一个元素上。
如果 initialValue 没有设置,且数组为空,将抛出TypeError 错误;如果 initialValue设置了但数组为空,accumulator 被设置为 initialValue,作为最终返回值,回调函数没有机会被调用。
- reduce 函数可以用来干嘛?
// 数组求和
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
// sum is 6
// 数组归并
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(accumulator, currentValue) {
return accumulator.concat(currentValue);
},
[]
);
// flattened is [0, 1, 2, 3, 4, 5]
更多示例,前往查看。