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

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


当前回答

使用reduce

设arr=[1,2,3,4];设和=arr.reduce((v,i)=>(v+i));console.log(总和);

其他回答

我认为这是求和数组的简单方法

function sumArray(arr){

    let total = 0;

    for(i = 0; i<arr.length ; i++){

        total += arr[i];
    }
    return total;
}

console.log(sumArray([1,2,3,4,]));

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

[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

没有人提到函数式编程,但在这种情况下使用Ramda是非常干净的方法:

//Assuming you use nodejs, but can also be used in browser
const R = require('ramda');

let nums = [2, 4, 6, 8, 10];
console.log(R.sum(nums));

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

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