Home >Web Front-end >JS Tutorial >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!