2013-10-09 81 views
-2

我的陣列看起來像這樣中數組索引的值:的Javascript得到一個數組

var array = [ 
    ['fred', 123, 424], 
    ['johnny', 111, 222] 
] 

等等

我只是想選擇第一個陣列中(第二值123,即「fred」數組中的值)如下所示:

array[0][1]; 

但它返回undefined。當我做CONSOLE.LOG(陣列),我得到如下:

Array[1], Array[1], Array[1], Array[1]] 
    0: Array[3] 
    0: "fred" 
    1: 123 
    2: 424 

等等

我如何使用上述語法,第二項的值?

謝謝!

下面是完整的代碼:

var addresses = [ 
    ['Bondi Beach Australia'], 
    ['Coogee Beach Australia'], 
    ['Cronulla Beach Australia'], 
    ['Manly Beach Australia'] 
]; 

for (i = 0; i < addresses.length; i++) { 
    (function(address){ 

     geocoder.geocode({ 'address': addresses[i][0]}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       address.push(results[0].geometry.location.lb); 
       address.push(results[0].geometry.location.mb); 
      } else { 
       alert("Geocode was not successful for the following reason: " + status); 
      } 
     }); 

    })(addresses[i]); 
} 

console.log(addresses[0][1]); // Returns 'undefined' 
+0

* 「它返回undefined」 *?你能顯示你的確切代碼嗎?順便說一句,這就是你應該如何訪問這個元素。 –

+3

的「示例」陣列和「真實的」陣列具有不同的結構(前者是2深,後者是3-深)。爲什麼即使給出一個例子,如果它是誤導? '地址[0] [0] [1]'會起作用。 – Jon

+0

在我的真實的例子,我用「推」到的循環 –

回答

3

您的問題是geocode是一個異步功能,您登錄它完成之前

當你在一個循環中啓動您查詢,您可能要等到所有的人才能完成,你做其他操作(其中包括你的日誌)前。

這裏有一個解決方案:

var n = addresses.length; 
function check() { 
    if (--n===0) { 
     // everything's finished 
     console.log(addresses[0][1]); 
    } 
} 
for (i = 0; i < addresses.length; i++) { 
    (function(address){ 
     geocoder.geocode({ 'address': addresses[i][0]}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       address.push(results[0].geometry.location.lb); 
       address.push(results[0].geometry.location.mb); 
      } else { 
       alert("Geocode was not successful for the following reason: " + status); 
      } 
      check(); 
     }); 
    })(addresses[i]); 
} 
+0

我們有一個經典的「你的代碼是異步」的問題了嗎? – Mathletics

+0

@Mathletics是的,有一個。但我認爲在這裏,因爲存在循環和許多異步功能,所以有機會變得更有幫助。 –

+0

鏈接到提到的規範? –