hacker0limbo/my-blog

JavaScript中高阶函数原生实现

hacker0limbo opened this issue · 0 comments

reduce

说明

引用自 MDN:

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值

语法为:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

callback 接受 4 个参数

  • Accumulator(acc): 累加器, 每次迭代结果均存在此, 当最后一次迭代结束时, 返回该累加器的结果
  • Current Value(cur): 当前(下一个)被用于计算的值, 用于累计到 acc 累加器中
  • Current Index (idx): 当前被计算元素的索引, 由于第一个数已被作为累加器的初始值, 所以默认从第二个数开始计算, 所以初始索引为 1. 如果提供了初始值(initialValue), 从第一个数开始计算, 初始索引为 1
  • array: 调用 reduce() 的数组

initialValue: 作为第一次调用 callback函数时的第一个参数的值, 如果没有提供初始值, 则将使用数组中的第一个元素.

例子:

const add = (a, b) => a + b

[1, 2, 3, 4].reduce(add) // 10
[1, 2, 3].reduce((acc, next) => {
  return {
    ...acc,
    [next]: next * 5
  }
}, {}) // { '1': 5, '2': 10, '3': 15 }

实现

几个注意点:

  • 第二个参数 initialValue 是否提供进行判断
  • 如果提供了 initialValue, 第一个参数回调函数中 index 需要从 0 开始计数, 否则为 1
Array.prototype.myReduce = function(callback, initialValue) {
  let acc = initialValue
  let i = 0
  if (typeof initialValue === 'undefined') {
    acc = this[0]
    i = 1
  }

  for (i; i < this.length; i++) {
    acc = callback(acc, this[i], i, this)
  }
  return acc
}

参考