reduce() 方法是数组的一个实例方法(共有方法),可以被数组的实例对象调用。reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。
- arr.reduce(callback[, initialValue]) {}
回调函数中可以传递四个参数。
previousValue:上一次调用回调函数返回的值,或者是提供的初始值(initialValue)
currentValue:数组中当前被处理的元素
currentIndex:当前被处理元素在数组中的索引, 即 currentValue 的索引. 如果有 initialValue 初始值, 从 0 开始. 如果没有从 1 开始
array:调用 reduce 的数组
initialValue:可选参数, 作为第一次调用 callback 的第一个参数
reduce() 返回值是最后一次调用回调函数返回的结果
reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:
回调函数第一次执行时,previousValue 和 currentValue 可能是两个不同值其中的一个,如果 reduce 有 initialValue 参数,那么 previousValue 等于 initialValue ,并且 currentValue 等于数组中的第一个值;如果 reduce 没有 initialValue 参数,那么 previousValue 等于数组中的第一个值,currentValue 等于数组中的第二个值。
注意: 如果没有 initialValue 参数, reduce 从 index 为 1 开始执行回调函数, 跳过第一个 index。 如果有 initialValue 参数, reduce 将从 index 为 0 开始执行回调
如果数组是空的并且没有 initialValue 参数, 将会抛出 TypeError 错误. 如果数组只有一个元素并且没有初始值 initialValue, 或者有 initialValue 但数组是空的, 这个唯一的值直接被返回而不会调用回调函数。
通常来说提供一个 initialValue 初始值更安全一点, 因为没有的话会出现如下输出结果。
- //没有提供initialValue
- function foo() {
- return [1, 2, 3, 4, 5].reduce((x, y) = >x + y); //15
- };
- console.log(foo.call(this));
- function foo() {
- return [].reduce((x, y) = >x + y); //TypeError
- };
- console.log(foo.call(this));
- //提供initialValue
- function foo() {
- return [].reduce((x, y) = >x + y, 0); //0
- };
- console.log(foo.call(this));
- [0, 1, 2, 3, 4].reduce((previousValue, currentValue, index, array) = >previousValue + currentValue);
回调被执行四次,每次的参数和返回值如下表:
reduce 的返回值是回调函数最后一次被调用的返回值(10)。
如果把初始值作为第二个参数传入 reduce,结果如下,结果如下:
- [0, 1, 2, 3, 4].reduce((previousValue, currentValue, index, array) = >previousValue + currentValue, 10);
最后一次函数调用的返回值 (20) 作为 reduce 函数的结果被返回
注意:添加了 initialValue 参数会多调用一次回调函数
- let sum = [0, 1, 2, 3, 4].reduce((x, y) = >x + y, 0);
- // 10
- let arr = [[1, 2], [3, 4], [5, 6]].reduce((x, y) = >x.concat(y), []);
- // [1, 2, 3, 4, 5, 6]
来源: http://www.cnblogs.com/Uncle-Keith/p/6164055.html