Home  >  Article  >  Web Front-end  >  How to sum arrays in JavaScript

How to sum arrays in JavaScript

青灯夜游
青灯夜游Original
2021-06-17 17:46:194580browse

Methods for JavaScript array summation: 1. Use recursion to continuously add and sum the array elements; 2. Use for loops to continuously add and sum the array elements; 3. Use forEach to traverse and let the array The elements are continuously added and summed; 4. Use the "eval(arr.join(" "))" statement to sum.

How to sum arrays in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript array summation

Method 1. Regardless of algorithm complexity, use recursion:

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));
  }
}

Method 2. Regular loop:

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

Method 3. Functional programming map-reduce:

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

Method 4. forEach traversal:

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

Method 5. eval:

function sum(arr) {
  return eval(arr.join("+"));
};
//测试输出运行结果:
console.log(sum([ 1, 2, 3, 4 ]))

The following results can be obtained:

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to sum arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn