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(" "))".
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:
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);
Method 3: Use eval() method
var a = [12, 13, 14], sum = 0; sum=eval(a.join("+")); console.log(sum);
[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!