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

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

使用贴图:

var sum = 0;
arr.map(function(item){
    sum += item;
});

// sum now contains the total.

您可以将该方法添加到Array原型中。

Array.prototype.sum = function(){
    var sum = 0;
    this.map(function(item){
        sum += item;
    });
    return sum;
}

然后您可以在任何阵列上使用它,如下所示:

arr.sum();

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

有人在找像我这样的功能性的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,因此如果需要,可以将其用作偏移量。还要注意,需要这个初始值,否则使用空数组调用函数将出错。

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

[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