hacker0limbo / my-blog

个人博客
5 stars 1 forks source link

JavaScript中高阶函数原生实现 #4

Open hacker0limbo opened 5 years ago

hacker0limbo commented 5 years ago

reduce

说明

引用自 MDN:

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

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

callback 接受 4 个参数

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 }

实现

几个注意点:

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
}

参考