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
    }
    
  • 相关阅读:
    用VisualSVN做项目版本控制
    jQuery 停止动画
    jQuery 效果
    jQuery 效果
    jQuery 效果
    jQuery 事件
    jQuery 选择器
    jQuery 语法(一)
    Form.ShowWithoutActivation 属性
    C#里面中将字符串转为变量名
  • 原文地址:https://www.cnblogs.com/zhangrunhao/p/9202806.html
Copyright © 2011-2022 走看看