Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2023-01-06 11:17:54
Original
3182 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

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