Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hacker0limbo opened this issue Oct 10, 2019 · 0 comments
Open

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

hacker0limbo opened this issue Oct 10, 2019 · 0 comments
Labels
javascript 原生 JavaScript 笔记整理

Comments

@hacker0limbo
Copy link
Owner

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
}

参考

@hacker0limbo hacker0limbo added the javascript 原生 JavaScript 笔记整理 label Oct 10, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
javascript 原生 JavaScript 笔记整理
Projects
None yet
Development

No branches or pull requests

1 participant