Home > Web Front-end > JS Tutorial > How do I calculate the sum and average of array elements in JavaScript?

How do I calculate the sum and average of array elements in JavaScript?

Patricia Arquette
Release: 2024-11-11 04:46:02
Original
429 people have browsed it

How do I calculate the sum and average of array elements in JavaScript?

Computing the Sum and Average of Array Elements

In your code, you're encountering difficulties in calculating the sum and average of an array. To resolve this, let's analyze the issue and implement a solution:

Calculate Sum:

To sum the array elements, you can use a loop that iterates over each element and adds it to a running total. In your code, this would look like:

var sum = 0;
for (i = 0; i < elmt.length; i++) {
  sum += parseInt(elmt[i]);
}
Copy after login

Note that we use parseInt to convert the string elements to integers for accurate calculation.

Calculate Average:

Once you have the sum, you can calculate the average by dividing the sum by the number of elements in the array:

var avg = sum / elmt.length;
Copy after login

Update Your Code:

Having calculated the sum and average, you can update the code within the loop to display the results:

for (i = 0; i < 10; i++) {
  document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>");
}
Copy after login

The above is the detailed content of How do I calculate the sum and average of array elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template