手写 数组 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

猜你喜欢

转载自blog.csdn.net/Luckyzhoufangbing/article/details/108906244
今日推荐