JS 手写 reduce 函数

663 阅读1分钟
  1. 手写 reduce 函数,附 MDN权威用法
Array.prototype.customReduce = function(fn, initVal){
    if(typeof fn != 'function'){
        throw Error("拜托欸,输个函数好不好!");
    }
    let pre = initVal ? initVal : 0;
    for(let i=0;i<this.length;i++){
        pre = pre + this[i];
    }
    return pre;
}

截屏2021-08-19 上午12.12.41.png