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

时间:2014-09-25 13:07:48

标签: javascript arrays undefined

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

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),它提供以下内容:

enter image description here

然后我点击了aray括号,它将我带到以下(这是正确的信息)。

enter image description here

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

1 个答案:

答案 0 :(得分:1)

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

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