以下为ChatGPT自动生成的解答,正确与否请自行判断。
BFE.devAI解答 - JavaScript 代码题
146. 实现Array.prototype.reduce()
Array.prototype.myReduce = function(callback, initialValue) {
let accumulator = initialValue === undefined ? undefined : initialValue;
for (let i = 0; i < this.length; i++) {
if (accumulator !== undefined) {
accumulator = callback.call(undefined, accumulator, this[i], i, this);
} else {
accumulator = this[i];
}
}
return accumulator;
}
这里的实现基本上跟原reduce()
函数一致,遍历数组并给定初始值。在循环中使用给定的回调函数将每个元素归纳为单个值,返回最终值。需要注意的是,如果没有给定初始值,那么第一个元素将作为初始值传递给回调函数。