js实现reduce


实现 JavaScript 的 reduce 方法
reduce 是 JavaScript 数组的高阶函数,用于将数组元素通过回调函数累加为单个值。以下是手动实现 reduce 的方法:
基本实现
Array.prototype.myReduce = function(callback, initialValue) {
let accumulator = initialValue !== undefined ? initialValue : this[0];
let startIndex = initialValue !== undefined ? 0 : 1;
for (let i = startIndex; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
};
使用示例
const arr = [1, 2, 3, 4];
const sum = arr.myReduce((acc, curr) => acc + curr, 0);
console.log(sum); // 输出: 10
关键点说明
- 初始值
initialValue是可选的。如果未提供,默认使用数组第一个元素作为初始值,并从第二个元素开始迭代。 - 回调函数接收四个参数:累加器
accumulator、当前元素currentValue、当前索引currentIndex和原数组array。 - 每次迭代将回调函数的返回值赋给累加器。
边界情况处理
// 空数组且无初始值会报错
[].myReduce((acc, curr) => acc + curr); // 抛出 TypeError
进阶实现(支持链式调用)
Array.prototype.myReduce = function(callback, initialValue) {
if (this.length === 0 && initialValue === undefined) {
throw new TypeError('Reduce of empty array with no initial value');
}
let accumulator = initialValue !== undefined ? initialValue : this[0];
for (let i = initialValue !== undefined ? 0 : 1; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
};






