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

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


当前回答

getTotal = (arr) => {
    let total = 0
    for (let i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total
}

getTotal([1, 2, 3, 4]) // 10
getTotal([1, 2, 3, 4, 5]) // 15

其他回答

带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

这要容易得多

function sumArray(arr) {
    var total = 0;
    arr.forEach(function(element){
        total += element;
    })
    return total;
}

var sum = sumArray([1,2,3,4])

console.log(sum)

这里有一个优雅的单线解决方案,它使用堆栈算法,尽管人们可能需要一些时间来理解这个实现的美。

const getSum = arr => (arr.length === 1) ? arr[0] : arr.pop() + getSum(arr);

getSum([1, 2, 3, 4, 5]) //15

基本上,该函数接受一个数组,并检查该数组是否正好包含一个项。如果为false,则从堆栈中弹出最后一项并返回更新的数组。

这段代码的妙处在于,该函数包括arr[0]检查,以防止无限循环。一旦到达最后一项,它将返回全部金额。

标准JavaScript解决方案:

var addition = [];
addition.push(2);
addition.push(3);

var total = 0;
for (var i = 0; i < addition.length; i++)
{
    total += addition[i];
}
alert(total);          // Just to output an example
/* console.log(total); // Just to output an example with Firebug */

这对我有用(结果应该是5)。我希望这种解决方案没有隐藏的缺点。

没有人提到函数式编程,但在这种情况下使用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));