Most aspects have been covered by the other responses, particularly RobG. To enhance your loops, consider following these guidelines that I typically follow:
1) Ensure the index is the first declared element, the array's length (for caching) is the second, and any additional variables follow them.
2) Enclose your loop code in brackets to separate it from the rest of the function. This makes it clear when to return the average product (after the }
).
Below is a slightly revised version of your code for your reference:
for (var index = 0, len = arrayavg.length, avg = 0; index < len; index++) {
avg += parseInt(arrayavg[index], 10) / len;
}
return avg;
Remember to specify a radix (in this case 10) in the parseInt
function. While it's optional, including it is considered good practice.
Additionally, here's an alternative function using a functional approach with reduce
that you may find helpful:
var arrayAverage = function (arr) {
return arr.reduce(function (a, b) { return a + b; }) / arr.length;
}