Javascript Data Type How to - Get average of an array








Question

We would like to know how to get average of an array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from  w ww.j  ava 2  s.  com-->
var score = [1,2,3,4,5,6,7,8,9,8,7,6,5,4];
var total = 0;
for (var i = 0; i < score.length; i++) {
   total += score[i];
}
average = (total / score.length).toFixed(2);

document.writeln("The average of those scores is: " + average);
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: