Array.prototype.reduce

源碼實現如下:

Array.prototype.myreduce = function (callback, accumulator) {

  let i = 0
  if (!accumulator) {
    i = 1
    accumulator = arr[0]
  }
  for (; i < this.length; i++) {
    accumulator = callback(accumulator, this[i], i, this)
  }
  return accumulator
}


const arr = [1, 2, 3, 4]
let arr1 = arr.myreduce(function (accumulator, currentValue, index, arr) {
  return accumulator + currentValue
}, 22)
console.log(arr1)     // 32
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章