Javascript获取数组中数组索引的值

时间:2013-10-09 15:35:04

标签: javascript arrays

我的数组看起来像这样:

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

等...

我只想在第一个数组中选择第二个值(123,即“fred”数组中的值),如下所示:

array[0][1];

但它返回未定义。当我做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'

1 个答案:

答案 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]);
}