How to find the sum of an array of numbers

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

    A few people have suggested adding a .sum() method to the Array.prototype. This is generally considered bad practice so I'm not suggesting that you do it.

    If you still insist on doing it then this is a succinct way of writing it:

    Array.prototype.sum = function() {return [].reduce.call(this, (a,i) => a+i, 0);}
    

    then: [1,2].sum(); // 3

    Note that the function added to the prototype is using a mixture of ES5 and ES6 function and arrow syntax. The function is declared to allow the method to get the this context from the Array that you're operating on. I used the => for brevity inside the reduce call.

提交回复
热议问题