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

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


当前回答

试试这个。。。

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

其他回答

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

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

可以将reduce()方法与lambda表达式结合使用:

[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);

标准JavaScript解决方案:

var addition = [];
addition.push(2);
addition.push(3);

var total = 0;
for (var i = 0; i < addition.length; i++)
{
    total += addition[i];
}
alert(total);          // Just to output an example
/* console.log(total); // Just to output an example with Firebug */

这对我有用(结果应该是5)。我希望这种解决方案没有隐藏的缺点。

这可以通过循环所有项,并在每次迭代中将它们添加到一个和变量中来实现。

var array = [1, 2, 3];

for (var i = 0, sum = 0; i < array.length; sum += array[i++]);

JavaScript不知道块的作用域,所以可以访问sum:

console.log(sum); // => 6

同上,但注释和准备为简单函数:

function sumArray(array) {
  for (
    var
      index = 0,              // The iterator
      length = array.length,  // Cache the array length
      sum = 0;                // The total amount
      index < length;         // The "for"-loop condition
      sum += array[index++]   // Add number on each iteration
  );
  return sum;
}