Home >Web Front-end >JS Tutorial >How to calculate the sum of one-dimensional array elements in JavaScript
Method: 1. Use “for(var i=0;i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. Use the for statement to traverse the array and find the sum
var a = [10, 11, 12], sum = 0; for (var i = 0; i < a.length; i ++) { sum += a[i]; }; console.log(sum); //返回33
2. Use the for in statement to traverse the array. Sum
var a = [10, 11, 12], sum = 0; for (var i in a) { //遍历数组 sum += a[i]; } console.log(sum); //返回33
3. Use forEach to traverse the array and sum
var a = [10, 11, 12], sum = 0; a.forEach (function (value) { sum += value; }); console.log(sum); //返回33
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to calculate the sum of one-dimensional array elements in JavaScript. For more information, please follow other related articles on the PHP Chinese website!