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

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


当前回答

带ES6休息参数

让数组=[1,2,3,4]函数和(…数字){设总数=0;for(常量数){总数+=数量;}回报总额;}console.log(sum(…array));

其他回答

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

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

我看到所有答案都是“减少”解决方案

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

使用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 total = 0;
$.each(arr,function() {
    total += this;
});
arr.reduce(function (a, b) {
    return a + b;
});

参考:Array.prototype.reduce()