无法访问Javascript数组中的变量。Console.log表示未定义

无法访问Javascript数组中的变量。Console.log表示未定义,javascript,arrays,undefined,Javascript,Arrays,Undefined,我有一个对象,其中包含一个数组,然后我将该数组传递给另一个函数,以便该函数使用。唯一的问题是,当我访问这些变量时,console.log说它们是未定义的。奇怪的是,当我记录整个数组时,它的值就在那里,但是当我访问数组元素时,它返回未定义的值。 这是我的密码: googleMapsFunctions.prototype.calculateDistances = function() { var that = this; console.log(that.la

我有一个对象,其中包含一个数组,然后我将该数组传递给另一个函数,以便该函数使用。唯一的问题是,当我访问这些变量时,console.log说它们是未定义的。奇怪的是,当我记录整个数组时,它的值就在那里,但是当我访问数组元素时,它返回未定义的值。 这是我的密码:

googleMapsFunctions.prototype.calculateDistances = function() {
        var that = this;    
        console.log(that.latLngArray);
        var closeClubs = [];
        var sortable = [];
        var resultsArray = [];
        jQuery(this.clubs).each(function(key, club) {
            var clubLatLng = new google.maps.LatLng(club.latitude, club.longitude);         
            var distanceFromLoc = clubLatLng.distanceFrom(that, "", "");        
            //alert(distanceFromLoc);
            //that.clubs[key].distance = distanceFromLoc;
            //closeClubs.push(club);
        });
        closeClubs.sort(function(a, b) {
            return a.distance - b.distance;
        });

    }

googleMapsFunctions.prototype.setLatLng = function() {
        var that = this;
        this.geocoder.geocode({'address' : this.location}, function(results, status) {
            if(status === "OK") {                   
                that.latLngArray.push(parseFloat(results[0].geometry.location.lat()));
                that.latLngArray.push(parseFloat(results[0].geometry.location.lng()));                  
            }               
        });
    }
//客户端代码

var googleMapsClass = new googleMapsFunctions(JSONItems, searchTerm);
    googleMapsClass.setLatLng();        
    googleMapsClass.calculateDistances();
我使用console.log打印出数组(that.latLngArray),该数组提供以下内容:

然后我点击aray括号,它会带我进入以下内容(这是正确的信息)

我似乎无法访问这些变量,它说它们是未定义的。 有人能看到这里发生了什么吗?
谢谢

最简单的方法就是在回调中移动距离计算:

googleMapsFunctions.prototype.setLatLng = function() {
    var that = this;
    this.geocoder.geocode({'address' : this.location}, function(results, status) {
        if(status === "OK") {                   
            that.latLngArray.push(parseFloat(results[0].geometry.location.lat()));
            that.latLngArray.push(parseFloat(results[0].geometry.location.lng()));
            // now it's safe to check the distances
            that.calculateDistances();
        }               
    });
}

从您发布的代码中还不清楚,但这很可能是一个需要异步操作同步完成的代码问题。还有一个Google地图地理代码也被调用。我将把它添加到代码示例中。好的,好了。对“setLatLng”的调用将在启动(但没有完成)GoogleAPI调用后立即返回。这有什么办法吗?你可以使用承诺机制,或者你可以在对地理代码的回调中进行距离计算。