How to find the sum of an array of numbers

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

    This is possible by looping over all items, and adding them on each iteration to a sum-variable.

    var array = [1, 2, 3];
    
    for (var i = 0, sum = 0; i < array.length; sum += array[i++]);
    

    JavaScript doesn't know block scoping, so sum will be accesible:

    console.log(sum); // => 6
    

    The same as above, however annotated and prepared as a simple function:

    function sumArray(array) {
      for (
        var
          index = 0,              // The iterator
          length = array.length,  // Cache the array length
          sum = 0;                // The total amount
          index < length;         // The "for"-loop condition
          sum += array[index++]   // Add number on each iteration
      );
      return sum;
    }
    

提交回复
热议问题