js实现reduce
实现 reduce 方法
在 JavaScript 中,reduce 是一个高阶函数,用于将数组中的元素通过指定的函数累积为单个值。以下是一个自定义实现的 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;
};
使用示例
假设需要对数组 [1, 2, 3, 4] 求和:

const arr = [1, 2, 3, 4];
const sum = arr.myReduce((acc, curr) => acc + curr, 0);
console.log(sum); // 输出 10
参数说明
-
callback:接收四个参数的函数:
accumulator:累积值,初始值为initialValue或数组的第一个元素。currentValue:当前处理的数组元素。currentIndex:当前元素的索引(可选)。array:调用reduce的数组本身(可选)。
-
initialValue(可选):作为第一次调用
callback时的第一个参数。如果未提供,则使用数组的第一个元素作为初始值。
注意事项
- 如果没有提供
initialValue,空数组调用reduce会抛出错误。 - 回调函数应确保返回累积值,否则后续迭代可能出错。
测试用例
// 求和
const sum = [1, 2, 3].myReduce((acc, val) => acc + val, 0);
console.log(sum); // 6
// 拼接字符串
const concat = ['a', 'b', 'c'].myReduce((acc, val) => acc + val, '');
console.log(concat); // 'abc'
// 扁平化数组
const flattened = [[0, 1], [2, 3], [4, 5]].myReduce(
(acc, val) => acc.concat(val),
[]
);
console.log(flattened); // [0, 1, 2, 3, 4, 5]
通过自定义实现 reduce,可以更好地理解其内部机制,并根据需求扩展功能。






