手写一个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

浙公网安备 33010602011771号