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

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


当前回答

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

其他回答

为什么不减少?这通常有点反直觉,但使用它求和非常简单:

var a = [1,2,3];
var sum = a.reduce(function(a, b) { return a + b; }, 0);

有人在找像我这样的功能性的oneliner吗?

假设:

const arr = [1, 2, 3, 4];

这是现代JS的一条直线:

sum = arr.reduce((a, b) => a + b, 0);

(如果您碰巧需要支持没有箭头功能的旧IE:)

sum = arr.reduce(function (a, b) {return a + b;}, 0);

注意,这里的初始值是0,因此如果需要,可以将其用作偏移量。还要注意,需要这个初始值,否则使用空数组调用函数将出错。

这些都是很好的答案,但如果数字是按照问题(1,2,3,4)中的顺序排列的话,你可以通过应用公式轻松地做到这一点(n*(n+1))/2,其中n是最后一个数字

此外,对于简单数组,使用es6求和。

const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0);
 
console.log(sum); 

对于具有默认初始化值的对象数组

const totalAmount = obj => 
    Object.values(obj).reduce((acc, { order_qty, mrp_price }) => 
    acc + order_qty * mrp_price, 0);
    
    console.log(totalAmount); 

试试这个。。。

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