How to find the sum of an array of numbers

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

    Cool tricks here, I've got a nit pick with a lot of the safe traditional answers not caching the length of the array.

    function arraySum(array){
      var total = 0,
          len = array.length;
    
      for (var i = 0; i < len; i++){
        total += array[i];
      }
    
      return total;
    };
    
    var my_array = [1,2,3,4];
    
    // Returns 10
    console.log( arraySum( my_array ) );
    

    Without caching the length of the array the JS compiler needs to go through the array with every iteration of the loop to calculate the length, it's unnecessary overhead in most cases. V8 and a lot of modern browsers optimize this for us, so it is less of a concern then it was, but there are older devices that benefit from this simple caching.

    If the length is subject to change, caching's that could cause some unexpected side effects if you're unaware of why you're caching the length, but for a reusable function who's only purpose is to take an array and add the values together it's a great fit.

    Here's a CodePen link for this arraySum function. http://codepen.io/brandonbrule/pen/ZGEJyV

    It's possible this is an outdated mindset that's stuck with me, but I don't see a disadvantage to using it in this context.

提交回复
热议问题