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

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


当前回答

标准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)。我希望这种解决方案没有隐藏的缺点。

其他回答

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

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

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

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

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

Object.defineProperty(Object.prototype, 'sum', {
    enumerable:false,
    value:function() {
        var t=0;for(var i in this)
            if (!isNaN(this[i]))
                t+=this[i];
        return t;
    }
});

[20,25,27.1].sum()                 // 72.1
[10,"forty-two",23].sum()          // 33
[Math.PI,0,-1,1].sum()             // 3.141592653589793
[Math.PI,Math.E,-1000000000].sum() // -999999994.1401255

o = {a:1,b:31,c:"roffelz",someOtherProperty:21.52}
console.log(o.sum());              // 53.519999999999996
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

有趣的方法:

eval([1,2,3].join("+"))

事实上,有一个古老而有趣的经典解决方案(除了新手“foreach”和“reduce”):的经典。

y = 0;
for (x of [1, 2, 3, 4]) y+=x;