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,若是咱們沒傳,那麼累加值的初始值就會是數組的第一個元素。this

    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
    }

stackblitzprototype

相關文章
相關標籤/搜索