Javascript array length of 0

后端 未结 3 1896
执笔经年
执笔经年 2021-01-16 09:16

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

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 10:10

    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.

提交回复
热议问题