js小拔高——写一个reduce

缘起:最近看油管里面有一个关于js面试的视频,里面提到了可能会让你写一写reduce等函数,于是也来一起小拔高拔高。

先写写map

  • 首先回忆平时是如何使用的map。

    // const newarr = arr.map(v=>v*v) 
  • 于是知道我们写的回调会被map调用,并且传一个v进来。

    Array.prototype.myMap = function (callback){
      const newArray = []
      this.forEach(ele => {
        newArray.push(callback(ele))
      })
      return newArray
    }

开始写reduce

  • 先上mdn查查reduce的具体参数和用法。

    // const afterReduceVal = arr.reduce((acc,cur,idx,src)=>{
    do something and return acc},init)
  • 也就是说reduce会调用我们的回调,并且传给我们累加值acc,当前值cur,当前索引idx,源数组src。其中累加值的初始值是我们传的init,如果我们没传,那么累加值的初始值就会是数组的第一个元素。

    Array.prototype.myReduce = function(callback,init) {
      let acc,idx;
      if(init){
        acc = init // 检测我们是不是传了init
        idx = 0
      } else {
        acc = this[0]
        idx = 1
      }
      for(let i = idx;i<this.length;i++) {
        acc = callback(acc,this[i],i,this)
      }
      return acc
    }

stackblitz

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章