给定一个数组[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

其他回答

arr.reduce(function (a, b) {
    return a + b;
});

参考:Array.prototype.reduce()

有人在找像我这样的功能性的oneliner吗?

假设:

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

这是现代JS的一条直线:

sum = arr.reduce((a, b) => a + b, 0);

(如果您碰巧需要支持没有箭头功能的旧IE:)

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

注意,这里的初始值是0,因此如果需要,可以将其用作偏移量。还要注意,需要这个初始值,否则使用空数组调用函数将出错。

有趣的方法:

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

Vanilla JavaScript是您所需要的一切:

> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(function(e){sum += e}); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(e => sum += e); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e in a) sum += e; sum
"00123foobar"
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e of a) sum += e; sum
10
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