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

How to sum an array in javascript

青灯夜游
青灯夜游Original
2021-10-19 17:03:273816browse

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

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

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

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!

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