Five common methods of summing JS arrays

The input

sum([ 1.2.3.4 ])
Copy the code

The output

10
Copy the code

Method one: do it recursively, regardless of algorithm complexity

function sum(arr) {
  var len = arr.length;
  if(len == 0) {return 0;
  } else if (len == 1) {return arr[0];
  } else {
    return arr[0] + sum(arr.slice(1)); }}Copy the code

Method 2. Conventional cycle

function sum(arr) {
  var s = 0;
  for (var i=arr.length-1; i>=0; i--) {
    s += arr[i];
  }
  return s;
}
Copy the code

Method 3: Functional programming map-reduce

function sum(arr) {
  return arr.reduce(function(prev, curr, idx, arr){
    return prev + curr;
  });
}
Copy the code

Method 4. ForEach traversal

function sum(arr) {
  var s = 0;
  arr.forEach(function(val, idx, arr) {
    s += val;
  }, 0);
  
  return s;
};
Copy the code

Method 5. Eval

function sum(arr) {
  return eval(arr.join("+"));
};

Copy the code

Test output run results

console.log(sum([ 1.2.3.4 ]))
Copy the code

Return result 10