Home > Web Front-end > JS Tutorial > How to sum an array in javascript

How to sum an array in javascript

青灯夜游
Release: 2021-10-19 17:04:57
Original
3818 people have browsed it

Method: 1. Use the statement "a.forEach(function(value){sum =value})"; 2. Use "a.reduce(function(pre,curr){sum=pre curr}) "; 3. Use "eval(a.join(" "))".

How to sum an array in javascript

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

javascript sums arrays

Method 1: Use forEach() method

forEach () method is used to call each element of the array and pass the element to the callback function.

Example: Accumulate and sum array values

var a = [10, 11, 12], sum = 0;
a.forEach(function(value) {
	sum += value;
});
console.log(sum);
Copy after login

Output result:

How to sum an array in javascript

Method 2: Use reduce() method

var a = [11, 12, 13], sum = 0;
a.reduce(function(pre,curr) {
	sum=pre+curr;
	return sum;
});
console.log(sum);
Copy after login

How to sum an array in javascript

Method 3: Use eval() method

var a = [12, 13, 14], sum = 0;
sum=eval(a.join("+"));
console.log(sum);
Copy after login

How to sum an array in javascript

[Recommended learning: javascript advanced tutorial]

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

Related labels:
source:php.cn
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