簡體   English   中英

調用javascript對象值會給我“未定義”

[英]Calling javascript object value gives me 'undefined'

我正在使用Google Map應用程序,我希望從數據庫中加載一些標記並將其顯示在地圖上。 因此,我創建了一個數組並定義了這樣的對象。

function shop_data(name,latitude,longitude,type)
    {
    this.name=name;
    this.latitude=latitude;
    this.longitude=longitude;
    this.type=type;
    }

然后,我將從ajax請求中檢索到的一些數據添加到“ shop_data”對象數組中。 該數組定義為“ all_shops”。

var i=0;
for(var o in data){
var name = data[o].name;
    var type = data[o].type;
var lat = data[o].lat;
var lng = data[o].lng;

all_shops[i]=new shop_data(name,lat,lng,type);
i++
}

然后,當我調用“ all_shops [i] .name”時,它給了我自己的名字。 但是當我叫“ all_shops [i] .lat”或“ all_shops [i] .lng”時,它給了我“未定義”。 我也嘗試解析經緯度。 此處lat,lng是MySQL數據庫中的雙變量。 我可以通過調用name,type,lat,lng從接收到的ajax數據中毫無問題地獲取lat,lng值。 但是,當我將它們全部放入一個數組並從數組中調用它們時,事情就出錯了。 任何幫助,將不勝感激。 謝謝。

this.latitude=latitude;
this.longitude=longitude;

this.lat=latitude;
this.lng=longitude;

您有一個簡單的復制/粘貼錯誤。

你應該打電話給你的latitudelongitudeall_shops[i]latlng ,你有你的shop_data函數定義是這樣

function shop_data(name,latitude,longitude,type)
{
   this.name=name;
   this.latitude=latitude;
   this.longitude=longitude;
   this.type=type;
}

或者如果要使用latlng則更改shop_data函數定義,例如

function shop_data(name,latitude,longitude,type)
{
   this.name=name;
   this.lat=latitude;
   this.lng=longitude;
   this.type=type;
}

更改變量名稱以使其匹配並進行一些清除可以得到:

function shop_data(name,latitude,longitude,type){
    this.name=name;
    this.lat=latitude;
    this.lng=longitude;
    this.type=type;
}

和:

var i=0;
for(var o in data){
    var name = data[o].name;
    var type = data[o].type;
    var lat = data[o].lat;
    var lng = data[o].lng;

    all_shops[i]=new shop_data(name,lat,lng,type);
    i++
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM