Javascript array length of 0

风格不统一 提交于 2019-12-01 14:41:14

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!