Reputation: 257
My array is declared like this
var stocks = new Array();
I'm getting a list of numbers from google trends and turning it into an array. This is console.log('The stocks are ', stocks);
The stocks are [47, 65, 81, 100, 86, 76, 57, 54, 80, 81, 92, 82, 81, 59, 48, 77, 90, 86]
Here's my average function. It returns NaN instead of the average.
function avgOut(values) {
var average = 0;
for (var i = 0; i < values.length; i = i + 1) {
average = average + values[i];
}
return (average / values.length); // returns NaN
}
Edit: Here's the jsfiddle http://jsfiddle.net/caduekL2/
Upvotes: 0
Views: 100
Reputation: 4138
Try this: http://jsfiddle.net/jvq1916d/
Just put console.log(avgOut(stocks));
right after console.log('The stocks are ', stocks);
Upvotes: 1
Reputation: 81
Guffa is correct, your average function is working correctly. You're getting NaN because the call to avgOut is happening BEFORE the call to Google's server returns.
Using JSONP makes the whole thing asynchronous, and you have to pay close attention to when you use variables.
The console.log(avgOut(stocks)) should happen in your callback function, which in this case looks like it starts at line 22 in that JSFiddle link.
Upvotes: 2