Array.prototype.myReduce = function(callback, initialValue) {
// 判断数组是否为空
if (this.length === 0) {
throw new TypeError('Reduce of empty array with no initial value');
}
// 判断是否提供了初始值,如果没有则将第一个元素作为初始值
let accumulator = initialValue !== undefined ? initialValue : this[0];
// 判断是否提供了初始值,如果没有则从索引 1 开始遍历
let startIndex = initialValue !== undefined ? 0 : 1;
// 遍历数组,对每个元素应用回调函数,并将结果累积到 accumulator 变量中
for (let i = startIndex; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
};
// 示例用法
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.myReduce((acc, curr) => acc + curr, 0); // 输出:15