Home >Web Front-end >JS Tutorial >How to calculate the sum of one-dimensional array elements in JavaScript

How to calculate the sum of one-dimensional array elements in JavaScript

青灯夜游
青灯夜游Original
2021-06-22 15:05:313197browse

Method: 1. Use “for(var i=0;i

How to calculate the sum of one-dimensional array elements in JavaScript

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

How to calculate the sum of one-dimensional array elements in JavaScript

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

How to calculate the sum of one-dimensional array elements in JavaScript

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

How to calculate the sum of one-dimensional array elements in JavaScript

[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!

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