给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[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
其他回答
我看到所有答案都是“减少”解决方案
var array = [1,2,3,4]
var total = 0
for (var i = 0; i < array.length; i++) {
total += array[i]
}
console.log(total)
var total = 0;
$.each(arr,function() {
total += this;
});
标准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;
}
有人在找像我这样的功能性的oneliner吗?
假设:
const arr = [1, 2, 3, 4];
这是现代JS的一条直线:
sum = arr.reduce((a, b) => a + b, 0);
(如果您碰巧需要支持没有箭头功能的旧IE:)
sum = arr.reduce(function (a, b) {return a + b;}, 0);
注意,这里的初始值是0,因此如果需要,可以将其用作偏移量。还要注意,需要这个初始值,否则使用空数组调用函数将出错。