给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
var total = 0;
$.each(arr,function() {
total += this;
});
其他回答
一小段JavaScript代码就能完成这项工作:
var numbers = [1,2,3,4];
var totalAmount = 0;
for (var x = 0; x < numbers.length; x++) {
totalAmount += numbers[x];
}
console.log(totalAmount); //10 (1+2+3+4)
标准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 sum = (arr) => arr.length === 1 ? arr[0] : arr.shift() + sum(arr);
sum([1,2,3,4]) // 10
使用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
对于真正大量的人来说,循环或减少可能是过程密集型的。使用高斯怎么样?
sum = (n * (n+1))/2;
来自mathcentral。