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
Patricia ArquetteOriginal
2024-11-11 04:46:02432browse

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]);
}

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;

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/>");
}

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!

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