请手动实现Array.prototype.reduce的方法

Array.prototype.reduce 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。

以下是一个手动实现的 reduce 方法的示例:

Array.prototype.myReduce = function(callback, initialValue) {
    // 如果没有提供初始值,则将数组的第一个元素作为初始值,并从数组的第二个元素开始进行迭代
    if (initialValue === undefined) {
        if (this.length === 0) {
            throw new TypeError('Reduce of empty array with no initial value');
        }
        initialValue = this[0];
        let start = 1;
    } else {
        let start = 0;
    }

    let accumulator = initialValue;
    for (let i = start; i < this.length; i++) {
        accumulator = callback(accumulator, this[i], i, this);
    }
    return accumulator;
};

// 使用示例
const array = [1, 2, 3, 4];
const sum = array.myReduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出:10

这个 myReduce 方法首先检查是否提供了初始值。如果没有提供初始值,那么它会检查数组是否为空。如果数组为空且没有提供初始值,那么会抛出一个 TypeError。如果数组不为空且没有提供初始值,那么它会将数组的第一个元素作为初始值,并从数组的第二个元素开始进行迭代。如果提供了初始值,那么它会从数组的第一个元素开始进行迭代。

在迭代过程中,它会使用提供的回调函数来计算累加值。回调函数接收四个参数:累加器、当前值、当前索引和原数组。在每次迭代中,它都会更新累加器的值,并在迭代结束后返回累加器的值。

posted @   王铁柱6  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示