Fastest JavaScript summation

前端 未结 10 2141
再見小時候
再見小時候 2020-11-27 15:13

What is the fastest way to sum up an array in JavaScript? A quick search turns over a few different methods, but I would like a native solution if possible. This will run un

10条回答
  •  再見小時候
    2020-11-27 15:38

    You should be able to use reduce.

    var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);
    

    Source

    And with arrow functions introduced in ES6, it's even simpler:

    sum = array.reduce((pv, cv) => pv + cv, 0);
    

提交回复
热议问题