reduce() 方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被用作初始值,迭代器将从第二个元素开始执行(即从索引为 1 而不是 0 的位置开始)。
callbackFn 的结果。在第一次调用时,如果指定了 initialValue 则为指定的值,否则为 array[0] 的值。array[0] 的值,否则为 array[1]。reduce() 的数组本身。Uncaught TypeError: Reduce of empty array with no initial value)。<script>
var arr = [1, 2, 3, 4];
var result = arr.reduce(function (accumulator, currentValue, currentIndex, array) {
console.log("accumulator----->", accumulator);
console.log("currentValue----->", currentValue);
console.log("currentIndex----->", currentIndex);
console.log("array----->", array);
return accumulator + currentValue;
}, -3);
console.warn("result----->", result);
script>
<script>
Array.prototype.kaimoReduce = function (callbackfn, initialValue) {
let hasInitialValue = initialValue !== undefined;
if (this.length === 0) {
if (hasInitialValue) {
return initialValue;
} else {
throw TypeError("Reduce of empty array with no initial value");
}
}
let accumulator = hasInitialValue ? initialValue : this[0];
let i = hasInitialValue ? 0 : 1;
for (i; i < this.length; i++) {
accumulator = callbackfn(accumulator, this[i], i, this);
}
return accumulator;
};
var result2 = arr.kaimoReduce(function (accumulator, currentValue, currentIndex, array) {
console.log("accumulator---kaimoReduce-->", accumulator);
console.log("currentValue---kaimoReduce-->", currentValue);
console.log("currentIndex---kaimoReduce-->", currentIndex);
console.log("array---kaimoReduce-->", array);
return accumulator + currentValue;
}, -3);
console.warn("result2---kaimoReduce-->", result2);
script>

数组为空数组以及没有初始值的时候,就直接报错提示
