How to find the sum of an array of numbers

后端 未结 30 2587
醉话见心
醉话见心 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)
    
    0 讨论(0)
  • 2020-11-21 14:21

    Here's an elegant one-liner solution that uses stack algorithm, though one may take some time to understand the beauty of this implementation.

    const getSum = arr => (arr.length === 1) ? arr[0] : arr.pop() + getSum(arr);
    
    getSum([1, 2, 3, 4, 5]) //15
    

    Basically, the function accepts an array and checks whether the array contains exactly one item. If false, it pop the last item out of the stack and return the updated array.

    The beauty of this snippet is that the function includes arr[0] checking to prevent infinite looping. Once it reaches the last item, it returns the entire sum.

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

    i saw all answers going for 'reduce' solution

    var array = [1,2,3,4]
    var total = 0
    for (var i = 0; i < array.length; i++) {
        total += array[i]
    }
    console.log(total)
    
    0 讨论(0)
  • 2020-11-21 14:23

    Funny approach:

    eval([1,2,3].join("+"))
    
    0 讨论(0)
  • 2020-11-21 14:23

    You can combine reduce() method with lambda expression:

    [1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);
    
    0 讨论(0)
  • 2020-11-21 14:24

    Anyone looking for a functional oneliner like me? Take this:

    sum= arr.reduce(function (a, b) {return a + b;}, 0);
    
    0 讨论(0)
提交回复
热议问题