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
}

转载于:https://www.cnblogs.com/zhangrunhao/p/9202806.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值