MDN-Array.prototype.reduce
介绍
reduce() 方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被作为初始值 initialValue,迭代器将从第二个元素开始执行(索引为 1 而不是 0)。
用法
1 2 3 4 5 6 7 8 9 10 11
| const array1 = [1, 2, 3, 4];
const initialValue = 0; const sumWithInitial = array1.reduce( (previousValue, currentValue) => previousValue + currentValue, initialValue );
console.log(sumWithInitial);
|
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| Array.prototype.reduceFn = function (reducer) { if (typeof reducer !== 'function') { throw new TypeError(`${reducer} is not a function.`); } const hasInitValue = arguments.length > 1; const array = Object(this); const length = array.length; if (length === 0 && !hasInitValue) { throw new TypeError('Reduce of empty array with no initial value'); } let previousValue = hasInitValue ? arguments[1] : array[0]; let currentIndex = hasInitValue ? 0 : 1; while (currentIndex < length) { previousValue = reducer(previousValue, array[currentIndex], currentIndex, array); currentIndex ++; } return previousValue; };
[1, 2, 3, 4, 5].reduceFn((prev, cur) => prev + cur); [1, 2, 3, 4, 5].reduceFn((prev, cur) => prev + cur, 10);
|