What does the Reduce() JavaScript function do?

末鹿安然 提交于 2019-12-09 03:36:25

问题


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?

Example:

var arr = [1,2,3,4,5,6];
arr.reduce(function(p,n){
 return p+n;
},0);
// Output 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?


回答1:


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:

  • 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



回答2:


reduce() method has two parameters: a callback function that is called for every element in the array and an initial value.

The callback function also has two parameters: an accumulator value and the current value.

The flow for your array ([1, 2, 3, 4, 5, 6]) is like this:

1. return 0 + 1 // 0 is the accumulator which the first time takes the initial value, 1 is the current value. The result of this becomes the accumulator for the next call, and so on..
2. return 1 + 2 // 1 - accumulator, 2 - current value
3. return 3 + 3 // 3 - accumulator, 3 - current value, etc...
4. return 6 + 4
5. return 10 + 5
6. return 15 + 6

And when reached to the end of the array, return the accumulator, which here is 21



来源:https://stackoverflow.com/questions/33392307/what-does-the-reduce-javascript-function-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!