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

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


当前回答

对于真正大量的人来说,循环或减少可能是过程密集型的。使用高斯怎么样?

sum = (n * (n+1))/2;

来自mathcentral。

其他回答

使用贴图:

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();

这正是减薪的工作。

如果您使用的是ECMAScript 2015(又名ECMAScript6):

constsum=[1,2,3]。reduce((partialSum,a)=>partialSum+a,0);console.log(总和);//6.

对于旧的JS:

常量sum=[1,2,3]。reduce(add,0);//数组为空时避免使用初始值函数add(累加器,a){返回蓄能器+a;}console.log(总和);//6.

这不是很漂亮吗?:-)

这些都是很好的答案,但如果数字是按照问题(1,2,3,4)中的顺序排列的话,你可以通过应用公式轻松地做到这一点(n*(n+1))/2,其中n是最后一个数字

    <!DOCTYPE html>
    <html>
    <body>

      <p>Click the button to join two arrays.</p>
      <button onclick="myFunction()">Try it</button>
      <p id="demo"></p>
    <script>
var hege = [1, 2,4,6,7,8,8];
var stale = [1, 2,4,5];
function myFunction() {
    console.log((hege.length > stale.length))    
    var children  = (hege.length > stale.length)? abc1() :abc2();       document.getElementById("demo").innerHTML = children;
}
function abc1(){
    console.log(hege,"Abc1")    
    var abcd=hege.map(function (num, idx) {
        console.log(hege.length , idx)
        return stale.length>idx?num + stale[idx]:num;
    })
    return abcd;
}

function abc2(){

    console.log(hege,"Abc2",stale)    
    var abcd=stale.map(function (num, idx) {
        console.log(hege.length , idx)
        return hege.length>idx?num + hege[idx]:num;
    })
    return abcd;
}
</script>

</body>
</html>

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

[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