How to find the sum of an array of numbers

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

    OK, imagine you have this array below:

    const arr = [1, 2, 3, 4];
    

    Let's start looking into many different ways to do it as I couldn't find any comprehensive answer here:

    1) Using built-in reduce()

    function total(arr) {
      if(!Array.isArray(arr)) return;
      return arr.reduce((a, v)=>a + v);
    }
    

    2) Using for loop

    function total(arr) {
      if(!Array.isArray(arr)) return;
      let totalNumber = 0;
      for (let i=0,l=arr.length; i

    3) Using while loop

    function total(arr) {
      if(!Array.isArray(arr)) return;
      let totalNumber = 0, i=-1;
      while (++i < arr.length) {
         totalNumber+=arr[i];
      }
      return totalNumber;
    }
    

    4) Using array forEach

    function total(arr) {
      if(!Array.isArray(arr)) return;
      let sum=0;
      arr.forEach(each => {
        sum+=each;
      });
      return sum;
    };
    

    and call it like this:

    total(arr); //return 10
    

    It's not recommended to prototype something like this to Array...

提交回复
热议问题