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

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


当前回答

无需初始值!因为如果没有传递初始值,则不会对列表的第一个元素调用回调函数,而是将第一个元素作为初始值传递。非常酷的功能:)

[1, 2, 3, 4].reduce((a, x) => a + x) // 10
[1, 2, 3, 4].reduce((a, x) => a * x) // 24
[1, 2, 3, 4].reduce((a, x) => Math.max(a, x)) // 4
[1, 2, 3, 4].reduce((a, x) => Math.min(a, x)) // 1

其他回答

也可以使用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

一小段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)

ES6用于。。属于

let total = 0;

for (let value of [1, 2, 3, 4]) {
    total += value; 
}

带reduce()

[1, 2, 3, 4].reduce((a, b) => a + b, 0); // 10

使用forEach()

let sum = 0;
[1, 2, 3, 4].forEach(n => sum += n);
sum; // 10

带参数

function arrSum(arr) { 
  sum = 0;  
  arr.forEach(n => sum += n); 
  return sum; 
}

arrSum([1, 2, 3, 4]) // 10
var total = 0;
$.each(arr,function() {
    total += this;
});