I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater tha
So what actually happens is that when you log your response it actually having length as 0. But after the asynchronous response is returned it has 42 items but length being a property is logged as number. But your response being an object is logged initially with zero items. But when the actual response is received the reference to the response object is updated and you see that the response is having 42 items and length is also 42. The below code is an example for that that to show after the setTimeout
is called the logged response is updated in the console.
var getTopSelection = function(callback) {
var topSelection = [];
markers=[1,2,3,4,5,6,7,8,9];
for(var i=0; i < markers.length; i++) {
if(markers[i].map !== null) {
var stationID = markers[i].id;
getTrips(stationID, function(response) {
topSelection.push({
StationID: i,
Trips: response
});
}, function(error) {
console.log(error);
})
}
}
callback(topSelection);
};
function getTrips(station,fun){
setTimeout(function(){
fun(["trip1","trip2","trip3"]);
},1000)
}
getTopSelection(function(response) {
console.log(response); //115
console.log(response.length); //116
})
Try executing this snippet(have modified accordingly to show what actually happens) in a Fiddle here. And observe the output in console as in stackoverflow snippet result it wont be visible. Here is snap of the Console Output
Hope it helps :)
Array Length returns 0
It seems you are trying to find the length of an object, not an actual array.
console.log
is not synchronous.
Your console.log
statements appear after you have called getTrips
but before the getTrips
callback has fired.
Effectively, you are trying to return the response from an asynchronous call.
response
is an object. Objects in JS are always referenced. You are logging that reference, and then the object gets updated with the new values (and the new length) when the getTrips
callbacks fire. The new object is reflected in the console.
response.length
is a number. You are logging it. Number values are not references. It is 0
because at the time you called console.log
it was 0
. The display doesn't update when the value changed because is a number and not an object.