How do i use a function to find the average of the values in an array of numbers passed as argument to a function.(using java script) thank you for your help...

Dabeam,

This is easy if your array to be both "dense" and "contiguously indexed", ( [0], [1], [2], [3] etc.) but far trickier if it is either "sparse" ( [2], [5], [12], [100] ) or if you are exploiting JavaScript array's "associative" properties ( , , , ).

Assuming your array to be dense and contiguous (which is most probably the case), try this:

function arrayAverage(a){
[INDENT]var runningTotal = 0;
for (var i=0; i<a.length; i++){
[INDENT]runningTotal += a[i];[/INDENT]
}
return runningTotal/a.length;[/INDENT]
}

The average is thus returned to the point in your program wherever arrayAverage() is called. eg.

var myArray = new Array(1, 2, 3);
var myAverage = arrayAverage(myArray);

or

alert( arrayAverage(new Array(1, 2, 3)) );

Enjoy

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.