How to find the sum of an array of numbers

后端 未结 30 2592
醉话见心
醉话见心 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:20

    A short piece of JavaScript code would do this job:

    var numbers = [1,2,3,4];
    var totalAmount = 0;
    
    for (var x = 0; x < numbers.length; x++) {
    
        totalAmount += numbers[x];
    }
    
    console.log(totalAmount); //10 (1+2+3+4)
    

提交回复
热议问题