How to find the sum of an array of numbers

后端 未结 30 2634
醉话见心
醉话见心 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:06

    // Given array 'arr'
    var i = arr.length;
    var sum = 0;
    while (--i) sum += arr[i];
    

    This will take on average 1.57 ms/run (measured over 1000 runs on an array of 100 random normal numbers), compared to 3.604 ms/run with the eval() method above and 2.151 ms/run with a standard for(i,length,++) loop.

    Methodology note: this test was run on a Google Apps Script server, so their javascript engines are pretty much the same as Chrome.

    EDIT: --i instead of i-- saves 0.12 ms each run (i-- is 1.7)

    EDIT: Holy expletive, never mind this whole post. Use the reduce() method mentioned above, it's only 1 ms/run.

提交回复
热议问题