I have a function foo
that takes in an array of objects called locations
and has a string, fourSquareUrl
, containing information to access the Foursquare API. I grab the data from the API and push it to the locationData
array.
When I try to access an index of the array, locationData[i]
, I get undefined. But when I console.log(locationData); the array is displayed correctly. Thanks for your help!
var locationData = [];
function foo(locations) {
for (x in locations) {
var fourSquareUrl = 'API information';
$.getJSON(fourSquareUrl, function(data) {
var foursquareLocation = data.response.venues;
if(foursquareLocation) {
var item = foursquareLocation[0];
if (item) {
var address = item.location.formattedAddress;
locationData.push(address);
}
else {
var noAddress = "No location data available";
locationData.push(noAddress);
}
}
})
}
}
// works correctly
console.log(locationData);
// results in 'undefined'
console.log(locationData[0]);