美文网首页
Array.prototype.reduce

Array.prototype.reduce

作者: 玲儿珑 | 来源:发表于2021-03-24 14:05 被阅读0次

    源码实现如下:

    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
    

    相关文章

      网友评论

          本文标题:Array.prototype.reduce

          本文链接:https://www.haomeiwen.com/subject/gmmxhltx.html