Fastest JavaScript summation

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

    one of the simplest, fastest, more reusable and flexible is:

    Array.prototype.sum = function () {
        for(var total = 0,l=this.length;l--;total+=this[l]); return total;
    }
    
    // usage
    var array = [1,2,3,4,5,6,7,8,9,10];
    array.sum()
    

提交回复
热议问题