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

149.[js]reduce 有什么作用? #149

Open
webVueBlog opened this issue Mar 31, 2020 · 1 comment
Open

149.[js]reduce 有什么作用? #149

webVueBlog opened this issue Mar 31, 2020 · 1 comment
Labels
JavaScript JavaScript

Comments

@webVueBlog
Copy link
Member

[软技能]

@webVueBlog webVueBlog added the JavaScript JavaScript label Mar 31, 2020
@webVueBlog
Copy link
Member Author

reduce对数组中的每个元素执行一个自定义的累计器,将其结果汇总为单个返回值
reduce的精华所在是将累计器逐个作用于数组成员上,把上一次输出的值作为下一次输入的值。
如果我们想实现一个功能将函数里的元素全部相加得到一个值,可能会这样写代码

const arr = [1, 2, 3]
let total = 0
for (let i = 0; i < arr.length; i++) {
    total += arr[i]
}
console.log(total) //6

但是如果我们使用 reduce 的话就可以将遍历部分的代码优化为一行代码

const arr = [1, 2, 3]
const sum = arr.reduce((acc, current) =>
acc + current, 0)
console.log(sum)

@webVueBlog webVueBlog changed the title 149.[软技能]reduce 有什么作用? 149.[js]reduce 有什么作用? Apr 1, 2020
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