2012-08-12 22 views
-1

我試圖從回調數組中獲取緯度和經度。數組有時在內部有一個對象,有時有兩個對象。無法使用javascript從數組中獲取值

Object { place={...}, reference={...}} OR [Object { place={...}, reference={...}}, Object { place={...}, reference={...}}]

Placemaker.getPlaces(text,function(o){ 
    console.log(o); 
    if (typeof o.match!=='undefined' || o.length==1){ 
    latitude=o.match.place.centroid.latitude, longitude=o.match.place.centroid.longitude; 
    console.log(latitude,longitude);} 
    /*else if(o=='null'){ 
     latitude='', longitude=''; 
    }*/ 
    else if (typeof o.match[0]!=='undefined' || o.match.length==2){ 
     latitude=o.match[0].place.centroid.latitude, longitude=o.match[0].place.centroid.longitude; 
    console.log(latitude,longitude); 
    } 

基本上我可以從具有一個目標的矩陣,而不是從緯度和經度當存在兩個對象集內。這是錯誤我得到

感謝大家的幫助 !

+0

如果我m沒有錯,不應該把'||'作爲'&&'?另外,在我看來,您可能想檢查是否首先定義了「o.match」,然後再檢查「o.match [0]」。 – Zhihao 2012-08-12 20:36:09

+0

如果'o.match'爲'undefined',那麼'if'條件將返回false,因此依賴於'o.match'的'else if'條件不是'undefined'是一個壞主意。 – 2012-08-12 20:36:17

+0

我試着先檢查,如果o.match不是未定義的,但仍然是TypeError:o.match.place是未定義的....代碼其他如果(typeof o.match!=='undefined'){ \t \t if( typeof o.match [0]!=='undefined'){ \t \t latitude = o.match [0] .place.centroid.latitude,longitude = o.match [0] .place.centroid.longitude; \t console.log(latitude,longitude); \t} \t} – 2012-08-12 20:47:15

回答

0

我想告訴你什麼是你的截圖是這個JavaScript數據結構:

var match = [ 
    { 
     place: { 
      centroid: {latitude: xx, longitude: yy}, 
      name: "London, England", 
      type: "Town", 
      woeld: "44418" 
     } 
     reference: {...} 
    }, 
    { 
     place: { 
      centroid: {latitude: xx, longitude: yy}, 
      name: "Germany", 
      type: "Country", 
      woeld: "23424829" 
     } 
     reference: {...} 
    } 
]; 

您將訪問的緯度和經度每個元素的數組像這樣:

for (var i = 0; i < match.length; i++) { 
    var centroid = match[i].place.centroid; 
    // latitude is centroid.latitude 
    // longitude is centroid.longitude 
}