How to find the sum of an array of numbers

后端 未结 30 3072
醉话见心
醉话见心 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条回答
  •  萌比男神i
    2020-11-21 14:29

    I am a beginner with JavaScript and coding in general, but I found that a simple and easy way to sum the numbers in an array is like this:

        var myNumbers = [1,2,3,4,5]
        var total = 0;
        for(var i = 0; i < myNumbers.length; i++){
            total += myNumbers[i];
        }
    

    Basically, I wanted to contribute this because I didn't see many solutions that don't use built-in functions, and this method is easy to write and understand.

提交回复
热议问题