Home > Web Front-end > JS Tutorial > How to sum arrays in JavaScript? Introduction to common methods

How to sum arrays in JavaScript? Introduction to common methods

青灯夜游
Release: 2020-12-11 18:04:35
forward
7791 people have browsed it

This article will share with you some common methods for summing JavaScript arrays. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to sum arrays in JavaScript? Introduction to common methods

Common methods for summing JS arrays

1. for loop

var arr = [1,2,3];
function sum(arr) {
  var s = 0;
  for (var i = 0;i<arr.length;i++) {
    s += arr[i];
  }
  return s;
}
console.log(sum(arr));//6
Copy after login

2. forEach traversal

var arr = [1,2,3];
function sum(arr) {
  var s = 0;
  arr.forEach(function(val, idx, arr) {
    s += val;
  }, 0);
  return s;
};
console.log(sum(arr));//6
Copy after login

3. reduce

var arr = [1,2,3];
function sum(arr) {
  return arr.reduce(function(acr, cur){
    return acr + cur;
  });
}
console.log(sum(arr));//6
Copy after login

4. Recursion

var arr = [1,2,3];
function sum(arr) {
  if(arr.length == 0){
    return 0;
  } else if (arr.length == 1){
    return arr[0];
  } else {
    return arr[0] + sum(arr.slice(1));
  }
}
console.log(sum(arr));//6
Copy after login

5. eval

var arr = [1,2,3];
function sum(arr) {
  return eval(arr.join("+"));
};
console.log(sum(arr));//6
Copy after login

For more programming-related knowledge, please visit: Programming Teaching! !

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

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template