手动实现一个Array.reduce 就可以深入理解Array.reduce

764 阅读1分钟

Array.reduce的实现原理

Array.prototype.myReduce = function(fn,init){
    let arr = this;
    let curent = init??arr[0];
    
    let i = init!=undefined?0:1;
    for(;i<arr.length;i++){
       curent = fn(curent,arr[i]) 
    }
    return curent
}

// 测试用例
[1,2,3,4].myReduce((a,b)=>{
    return a+b
}) // ==> 10

[1,2,3,4].myReduce((a,b)=>{
    return a+b
},10) // ==> 20