Javascript array length of 0

ffritz

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 than 0:

var getTopSelection = function(callback) {
    var topSelection = [];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, globalFromDate, globalToDate, function(response) {
                topSelection.push({
                    StationID: stationID,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})

And this is shown in the inspector, the "length: 42" belongs to line 115.

enter image description here

Question: Why does it show a length of 0 eventhough it clearly says it has a length of 42 one line before?

Quentin

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related