What does the Reduce() JavaScript function do?

后端 未结 2 1823
青春惊慌失措
青春惊慌失措 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条回答
  • 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
    0 讨论(0)
  • 2020-12-11 07:45

    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

    0 讨论(0)
提交回复
热议问题