How to find the sum of an array of numbers

后端 未结 30 3164
醉话见心
醉话见心 2020-11-21 13:36

Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)

I thought $.each might be useful,

30条回答
  •  庸人自扰
    2020-11-21 14:11

    This is much easier

    function sumArray(arr) {
        var total = 0;
        arr.forEach(function(element){
            total += element;
        })
        return total;
    }
    
    var sum = sumArray([1,2,3,4])
    
    console.log(sum)
    

提交回复
热议问题