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

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


当前回答

标准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 total = 0;
$.each(arr,function() {
    total += this;
});

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

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

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

标准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)。我希望这种解决方案没有隐藏的缺点。

使用for循环:

const array = [1, 2, 3, 4];
let result = 0;

for (let i = 0; i < array.length - 1; i++) {
  result += array[i];
}

console.log(result); // Should give 10

甚至是forEach循环:

const array = [1, 2, 3, 4];
let result = 0;

array.forEach(number => {
  result += number;
})

console.log(result); // Should give 10

为简单起见,请使用reduce:

const array = [10, 20, 30, 40];
const add = (a, b) => a + b
const result = array.reduce(add);

console.log(result); // Should give 100

我是JavaScript和一般编码的初学者,但我发现一种简单易行的方法可以将数组中的数字相加,如下所示:

    var myNumbers = [1,2,3,4,5]
    var total = 0;
    for(var i = 0; i < myNumbers.length; i++){
        total += myNumbers[i];
    }

基本上,我想贡献这一点,因为我没有看到很多不使用内置函数的解决方案,而且这种方法很容易编写和理解。