手写一个reduce函数

1 Array.prototype.myReduce = function (f, v) {
2     let sum = v || this[0] || 0
3     let curIndex = v ? 0 : 1
4     for (let i = curIndex; i< this.length; i++) {
5         sum = f(sum,this[i],i,this)
6     }
7     return sum;
8 }
let arr = [1, 2, 3]
let sum = arr.myReduce(function(s, c) {
   return s + c;
}, 0)
console.log(sum) // 6

 

posted @ 2022-06-07 15:24  李健威  阅读(32)  评论(0)    收藏  举报