Home >Web Front-end >JS Tutorial >How to Calculate the Sum and Average of Array Elements in JavaScript?
Computing Sum and Average of Array Elements
To calculate the sum and average of elements in an array, you can use a for loop or a more efficient method using array methods.
Using a For Loop:
let sum = 0; for (i = 0; i < elmt.length; i++) { sum += parseFloat(elmt[i]); } let average = sum / elmt.length;
Using Array Methods:
let sum = elmt.reduce((a, b) => parseFloat(a) + parseFloat(b), 0); let average = sum / elmt.length;
Here's the corrected code with the implemented calculations:
var i; var elmt = new Array(); elmt[0] = "0"; elmt[1] = "1"; elmt[2] = "2"; elmt[3] = "3"; elmt[4] = "4"; elmt[5] = "7"; elmt[6] = "8"; elmt[7] = "9"; elmt[8] = "10"; elmt[9] = "11"; // Calculate sum using for loop let sum = 0; for (i = 0; i < elmt.length; i++) { sum += parseFloat(elmt[i]); } // Calculate average using array method let average = sum / elmt.length; // Display results document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + average + "<br/>");
The above is the detailed content of How to Calculate the Sum and Average of Array Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!