js 实现reduce

实现reduce

/**
 *
 * @param {*} cb callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any): any 
 * @param {*} thisArg 
 */
Array.prototype._reduce = function (cb, initValue) {
    if (typeof cb !== 'function') {
        throw 'the parameter cb must be a function'
    }
    if (!Array.isArray(this)) {
        throw 'function _forEach must be used by Array'
    }
    const array = this

    // 没有初始值时,取第一个元素作为初始值,并且索引从1开始
    let result = initValue !== undefined ? initValue : arr[0]
    
    for (let index = 0; index < array.length; index++) {
        // index will start at 1 case we do not have a initValue
        if (initValue === undefined && index === 0) {
            continue;
        }
        const v = array[index]
        result = cb(result, v, index, this)
    }

    return result
}

console.log(getRandomArr(5)._reduce((total,cur)=>{
    console.log(total,cur);
    return total + cur
},0));
posted @ 2022-01-25 12:34  IslandZzzz  阅读(211)  评论(0编辑  收藏  举报