手写 数组 reduce 函数

(一)reduce 语法

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

reduce 接收两个参数

例子:

let arr = [1, 2, 3, 4, 5]
// 下标是奇数的元素和
var result = arr.reduce((total, item, index) => {
  total += (index % 2 ? item : 0)
  return total
}, 0)

console.log(result) // 6

初始值是 0

(二)下面来手写 reduce

Array.prototype.reduce = function (callback, initValue) {
  let result = initValue // result 赋值 为传过来的初始值
  for (var index = 0; index < this.length; index++) {
    result = callback(result, this[index], index, this) // 循环重新计算 result
  }
  return result // 返回result
}

调用:

Array.prototype.reduce = function (callback, initValue) {
  let result = initValue
  for (var index = 0; index < this.length; index++) {
    result = callback(result, this[index], index, this)
  }
  return result
}

// 下标是奇数的元素和
let arr = [1, 2, 3, 4, 5]
var res = arr.reduce((total, item, index) => {
  total += (index % 2 ? item : 0)
  return total
}, 0)

console.log(res) // 6

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值