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

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


当前回答

如果您恰好使用Lodash,则可以使用sum函数

array = [1, 2, 3, 4];
sum = _.sum(array); // sum == 10

其他回答

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

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

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)

事实上,有一个古老而有趣的经典解决方案(除了新手“foreach”和“reduce”):的经典。

y = 0;
for (x of [1, 2, 3, 4]) y+=x;

Vanilla JavaScript是您所需要的一切:

> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(function(e){sum += e}); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(e => sum += e); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e in a) sum += e; sum
"00123foobar"
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e of a) sum += e; sum
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