问题描述
我发现非常有用的函数 reduce()
,我正在使用它,但我不确定我是否理解它。任何人都可以帮我理解这个功能吗?
I found very useful function reduce()
, and I'm using it, but I'm not sure if I understand it properly. Can any one 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
这是我的理解:减少( )
循环遍历数组的每个元素并返回前一个+当前值。防爆。 0 + 1,1 + 2等。在这种情况下,此函数将返回[0] - 返回1; [1] - 返回3; [2] - 返回5,[3] - 返回7,[4] - 返回9,[5] - 返回11.下一步是什么?为什么它给出结果21?
This is my understanding: Reduce()
loop through every element of the array and returning 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. 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的初始值()
作为第二个参数。返回和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
这篇关于Reduce()JavaScript函数有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!