reduce

作者: bestCindy | 来源:发表于2021-01-11 22:19 被阅读0次
Array.prototype.reduce = function(callback, prev) {
    for (let i = 0; i < this.length; i++) {
        if (typeof prev === undefined) {
            prev = callback(this[i], this[i + 1], i + 1, this);
        } else {
            prev = callback(prev, this[i], i, this);
        }
    }
    return prev;
}

let r1 = [1, 2, 3, 4].reduce(function (prevValue, currentValue, currentIndex, array) {
    return prevValue + currentValue;
}, 0);

console.log(r1);//10

相关文章

网友评论

      本文标题:reduce

      本文链接:https://www.haomeiwen.com/subject/tbujaktx.html