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

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


当前回答

也可以使用reduceRight。

[1,2,3,4,5,6].reduceRight(function(a,b){return a+b;})

其结果输出为21。

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

其他回答

可以将reduce()方法与lambda表达式结合使用:

[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);
arr.reduce(function (a, b) {
    return a + b;
});

参考:Array.prototype.reduce()

考虑到您拥有阵列

const arr = [1, 2, 3, 4];

对我来说,最直观的方法是使用For in

let sum = 0;
for(var value in arr) {
    sum += arr[value];
}

console.log('Array:', arr);
console.log('Sum:', sum);

然而,您也可以使用箭头函数和reduce函数

const sum = arr.reduce(function (a, b) {
    return a + b;
}, 0);

console.log('Array:', arr);
console.log('Sum:', sum);

他们都会输出

Array: [ 1, 2, 3, 4]
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)