给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)

我认为每个美元可能有用,但我不确定如何实现它。


当前回答

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

其他回答

有趣的方法:

eval([1,2,3].join("+"))

使用reduce

设arr=[1,2,3,4];设和=arr.reduce((v,i)=>(v+i));console.log(总和);

var total = 0;
$.each(arr,function() {
    total += this;
});

试试这个。。。

function arrSum(arr){
    total = 0;  
    arr.forEach(function(key){
        total = total + key;            
    });
    return total;
}

您可以使用for of循环求和,如下所示:

let arr = [1, 2, 3, 4];
let total = 0;
for (let i of arr) {
  total += i;
}
console.log(total)