The code below alerts out nothing for lis, but does for list. Why is that? Note it is definitely getting through to the push line for lis.push 8 times.
var lis = [], lat, lng;
$.getJSON("/locations/locations_list", function(data) {
$.each(data.Locations, function(index, arr) {
lis.push({lat:'aa', lng:'aa'});
});
});
alert(lis);
var i, list = [], rlat=lat2-lat1, rlng=lng2-lng1;
for(i=0; i<500; i++){
lat = lat1 + rlat * Math.random();
lng = lng1 + rlng * Math.random();
list.push({lat:lat, lng:lng, data:i});
}
alert(list);
You’re alerting
lisbefore thegetJson‘s callback has executed, so the array hasn’t filled up yet. Note that jquery’s ajax callbacks are asynchronous, so even though the code looks equivalent to the second case, actual execution order isn’t, and so the results aren’t either…Try: