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

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


当前回答

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

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)

其他回答

标准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,4]
var total = 0
for (var i = 0; i < array.length; i++) {
    total += array[i]
}
console.log(total)

当数组由字符串组成时,必须更改代码。如果数组是数据库请求的结果,则可能是这种情况。此代码有效:

alert(
["1", "2", "3", "4"].reduce((a, b) => Number(a) + Number(b), 0)
);

这里,[“1”,“2”,“3”,“4”]是字符串数组,函数Number()将字符串转换为数字。

只需使用此功能:

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

  return pArray;
}

函数和(pArray){pArray=pArray.reduce(函数(a,b){返回a+b;}, 0);返回pArray;}var arr=[1,4,5];console.log(总和(arr));

对于真正大量的人来说,循环或减少可能是过程密集型的。使用高斯怎么样?

sum = (n * (n+1))/2;

来自mathcentral。