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

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


当前回答

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

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;
}

其他回答

了解底层流程的最简单答案:

let array = [10, 20, 30, 40, 50]
let total = 0

for(let i in array)
{
    total += array[i]
}

console.log(total)

&如果您已经熟悉底层流程,那么内置方法可以节省您的时间:

let array = [10, 20, 30, 40, 50]
let total = array.reduce((x, y) => x + y)
console.log(total)

这正是减薪的工作。

如果您使用的是ECMAScript 2015(又名ECMAScript6):

constsum=[1,2,3]。reduce((partialSum,a)=>partialSum+a,0);console.log(总和);//6.

对于旧的JS:

常量sum=[1,2,3]。reduce(add,0);//数组为空时避免使用初始值函数add(累加器,a){返回蓄能器+a;}console.log(总和);//6.

这不是很漂亮吗?:-)

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

也可以使用reduceRight。

[1,2,3,4,5,6].reduceRight(function(a,b){return a+b;})

其结果输出为21。

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

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