Array 方法 `reduce` 有什么作用? [英] What does the Array method `reduce` do?
问题描述
我发现了一个非常有用的函数reduce
,我正在使用它,但我不确定我是否理解正确.谁能帮我理解这个功能?
I found a very useful function reduce
, and I'm using it, but I'm not sure if I understand it properly. Can anyone help me to understand this function?
示例:
var arr = [ 1, 2, 3, 4, 5, 6 ];
arr.reduce(function(p,n){
return p + n;
}, 0);
// Output 21
这是我的理解:reduce
遍历数组的每个元素并返回previous + current value
.前任.0 + 1
, 1 + 2
等等.在这种情况下这个函数将返回:
This is my understanding: reduce
loops through every element of the array and returns previous + current value
. Ex. 0 + 1
, 1 + 2
etc. In this case this function will return:
[0] - return 1
[1] - return 3
[2] - return 5
[3] - return 7
[4] - return 9
[5] - return 11
接下来呢?为什么它给出结果 21
?
What next? Why does it give the result 21
?
推荐答案
摘自 此处,arr.reduce()
会将数组减少到回调指定的值.在您的情况下,它基本上会对数组的元素求和.步骤:
Taken from here, arr.reduce()
will reduce the array to a value, specified by the callback. In your case, it will basically sum the elements of the array.
Steps:
- 在 0,1 上调用函数(0 是作为第二个参数传递给
.reduce()
的初始值.返回 od 0 和 1 的总和,即 1. - 对前一个结果(即 1 )和下一个数组元素调用函数.这将返回 1 和 2 的总和,即 3
- 重复直到最后一个元素,总和为 21
- Call function on 0,1 ( 0 is the initial value passed to
.reduce()
as the second argument. Return sum od 0 and 1, which is 1. - Call function on previous result ( which is 1 ) and next array element. This returns sum of 1 and 2, which is 3
- Repeat until last element, which will sum up to 21
这篇关于Array 方法 `reduce` 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!