Fastest JavaScript summation

前端 未结 10 2128
再見小時候
再見小時候 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:15

    For your specific case, just use the reduce method of Arrays:

    var sumArray = function() {
        // Use one adding function rather than create a new one each
        // time sumArray is called
        function add(a, b) {
            return a + b;
        }
    
        return function(arr) {
            return arr.reduce(add);
        };
    }();
    
    alert( sumArray([2, 3, 4]) );
    

提交回复
热议问题