zoukankan      html  css  js  c++  java
  • Reduce实现

    Reduce实现

    参考

    第一版

    Array.prototype.fakeReduce = function (fn, base) {
      // this 指向原数组
      // 拷贝数据, 更改指针方向
      var arr = this.concat()
      // 处理默认值, arr就是我们要处理的叠加参数数组
      if (typeof base !== 'undefined') {
        arr.unshift(base)
      }
    
      let index; // 当前处理元素的索引
    
      while (arr.length > 2) { // 因为是需要前一项, 向后一项, 叠加, 所以需要两个元素以上
        index = this.length - arr.length + 1
        let newValue = fn.call(null, arr[0], arr[1], index, this)
        arr.splice(0, 2)
        arr.unshift(newValue)
      }
    
      index += 1
      let result = fn.call(null, arr[0], arr[1], index, this)
      return result
    }
    

    第二版: 使用splic直接替换元素

    Array.prototype.fakeReduce = function (fn, base) {
      var arr = this.concat()
      if (typeof base !== 'undefined') {
        arr.unshift(base)
      }
      while (arr.length > 1) {
        var index = this.length - arr.length + 1
        var result = fn.call(null, arr[0], arr[1], index, this)
        arr.splice(0, 2, result) // 使用splice直接替换
      }
      return result
    }
    

    第三版: 加上类型检测

    Array.prototype.fakeReduce = function (fn, base) {
      if (typeof fn !== 'function') {
        throw new TypeError('arguments[0] is not a funciton')
      }
      var arr = this.concat()
      if (typeof base !== 'undefined') {
        arr.unshift(base)
      }
      while (arr.length > 1) {
        var index = this.length - arr.length + 1
        var result = fn.call(null, arr[0], arr[1], index, this)
        arr.splice(0, 2, result) // 使用splice直接替换
      }
      return result
    }
    
  • 相关阅读:
    .NE 学习概要
    (转)工作之路---记录LZ如何在两年半的时间内升为PM
    XP下Winform背景透明问题
    CSE(Corrupted State Exceptions) 严重异常处理办法
    (转)C#模拟键盘鼠标事件
    (转).net项目技术选型总结
    (转)MSMQ续
    (转)MSMQ(消息队列)
    (转)TCP三次握手
    Socket编程初探
  • 原文地址:https://www.cnblogs.com/zhangrunhao/p/9202806.html
Copyright © 2011-2022 走看看