How to find the sum of an array of numbers

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

    If you happen to be using Lodash you can use the sum function

    array = [1, 2, 3, 4];
    sum = _.sum(array); // sum == 10
    
    0 讨论(0)
  • 2020-11-21 14:28
    var arr = [1,2,3,4];
    var total=0;
    for(var i in arr) { total += arr[i]; }
    
    0 讨论(0)
  • 2020-11-21 14:28

    When the array consists of strings one has to alter the code. This can be the case, if the array is a result from a databank request. This code works:

    alert(
    ["1", "2", "3", "4"].reduce((a, b) => Number(a) + Number(b), 0)
    );
    

    Here, ["1", "2", "3", "4"] ist the string array and the function Number() converts the strings to numbers.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 14:30
    arr.reduce(function (a, b) {
        return a + b;
    });
    

    Reference: Array.prototype.reduce()

    0 讨论(0)
  • 2020-11-21 14:30

    Use a for loop:

    const array = [1, 2, 3, 4];
    let result = 0;
    
    for (let i = 0; i < array.length - 1; i++) {
      result += array[i];
    }
    
    console.log(result); // Should give 10
    

    Or even a forEach loop:

    const array = [1, 2, 3, 4];
    let result = 0;
    
    array.forEach(number => {
      result += number;
    })
    
    console.log(result); // Should give 10
    

    For simplicity, use reduce:

    const array = [10, 20, 30, 40];
    const add = (a, b) => a + b
    const result = array.reduce(add);
    
    console.log(result); // Should give 100
    
    0 讨论(0)
提交回复
热议问题