手书きでreduceのソースコードを実现します.

718 ワード

/**
 *
 * @param callback          
 * @param prev      
 */
Array.prototype.reduce = function (callback,prev) {
    //  this   
    for (let i = 0; i < this.length; i++) {
        //          
        if (typeof prev === "undefined") {
            //     ,   callback,     ,    ,  index    ,    
            prev = callback(this[i], this[i + 1], i + 1, this);
        } else {
            //    ,   callback,  prev     ,       i,  index i,    
            prev = callback(prev, this[i], i, this);
        }
    }
    return prev;
};

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

console.log(r1);