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
    }
    
  • 相关阅读:
    Linux Ubuntu安装Mysql5.7
    Linux Ubuntu安装maven3.3.9
    Linux Ubuntu安装tomcat9
    Linux Ubuntu安装JDK1.8
    Win10 U盘安装ubuntu16.04 LTS 双系统
    Linux Mysql5.7 常用语句与函数
    在Linux CentOS 6.6上安装Python 2.7.9
    CentOS6下docker的安装和使用
    How to Install Apache Solr 4.5 on CentOS 6.4
    SpringBoot的日志管理
  • 原文地址:https://www.cnblogs.com/zhangrunhao/p/9202806.html
Copyright © 2011-2022 走看看