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

相关文章
相关标签/搜索