What does the Reduce() JavaScript function do?

后端 未结 2 1836
青春惊慌失措
青春惊慌失措 2020-12-11 07:10

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?

<
2条回答
  •  萌比男神i
    2020-12-11 07:36

    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

提交回复
热议问题