How to find the sum of an array of numbers

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

    Object.defineProperty(Object.prototype, 'sum', {
        enumerable:false,
        value:function() {
            var t=0;for(var i in this)
                if (!isNaN(this[i]))
                    t+=this[i];
            return t;
        }
    });
    
    [20,25,27.1].sum()                 // 72.1
    [10,"forty-two",23].sum()          // 33
    [Math.PI,0,-1,1].sum()             // 3.141592653589793
    [Math.PI,Math.E,-1000000000].sum() // -999999994.1401255
    
    o = {a:1,b:31,c:"roffelz",someOtherProperty:21.52}
    console.log(o.sum());              // 53.519999999999996
    

提交回复
热议问题