JavaScript数组长度为0 [英] Javascript array length of 0

查看:96
本文介绍了JavaScript数组长度为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容使我有些奇怪,它显示数组长度为0,即使在打印之前也表明长度明显大于0:

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
})

这在检查器中显示为长度:42".属于第115行.

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

问题:为什么它清楚地表示长度为42,但为什么仍显示0呢?

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

推荐答案

console.log 您的 console.log 语句在调用 getTrips 之后但在 getTrips 回调触发之前出现.

Your console.log statements appear after you have called getTrips but before the getTrips callback has fired.

有效地,您正在尝试返回响应从异步调用.

响应是一个对象.始终引用JS中的对象.您正在记录该引用,然后当 getTrips 回调触发时,对象将使用新值(和新长度)进行更新.新对象将反映在控制台中.

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 是一个数字.您正在记录它.数字值不是参考.它是 0 ,因为当时您调用 console.log 0 .当值更改为数字而不是对象时,显示不会更新.

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.

这篇关于JavaScript数组长度为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆