How to find the sum of an array of numbers

后端 未结 30 3247
醉话见心
醉话见心 2020-11-21 13:36

Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)

I thought $.each might be useful,

30条回答
  •  清歌不尽
    2020-11-21 14:12

    No need to initial value! Because if no initial value is passed, the callback function is not invoked on the first element of the list, and the first element is instead passed as the initial value. Very cOOl feature :)

    [1, 2, 3, 4].reduce((a, x) => a + x) // 10
    [1, 2, 3, 4].reduce((a, x) => a * x) // 24
    [1, 2, 3, 4].reduce((a, x) => Math.max(a, x)) // 4
    [1, 2, 3, 4].reduce((a, x) => Math.min(a, x)) // 1
    

提交回复
热议问题