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

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


当前回答

您可以使用for of循环求和,如下所示:

let arr = [1, 2, 3, 4];
let total = 0;
for (let i of arr) {
  total += i;
}
console.log(total)

其他回答

使用reduce

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

试试这个。。。

function arrSum(arr){
    total = 0;  
    arr.forEach(function(key){
        total = total + key;            
    });
    return total;
}
var total = 0;
$.each(arr,function() {
    total += this;
});
    <!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>

精确

对数组进行排序并以最小的数字开始求和(代码段显示了与非排序的区别)

[...arr].sort((a,b)=>a-b).reduce((a,c)=>a+c,0)

arr=[,6,9,1,1,1,1,.1,.1]sum=arr.reduce((a,c)=>a+c,0)sortSum=[…arr].sort((a,b)=>a-b).reduce((a、c)=>a+c,0)console.log('sum:',sum);console.log('sortSum:',sortSum);console.log('sum==sortSum:',sum==sortSum);//我们使用.sort((a,b)=>a-b)代替.sort(),因为//第二个将元素视为字符串(因此方式错误)//例如[1,10,9,20,93].sort()-->[1,10,20,9,93]

对于多维数字数组,使用arr.flat(无限)

arr=[[[1,2,3,4],[1,2,3,4],[1,2,4],[ [1,2,3,4],[1,2,3,4],[1,2,3,4] ] ];sum=arr.flat(无限).reduce((a,c)=>a+c,0);console.log(总和);//60