-2

我的数组如下所示:

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

ETC...

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

array[0][1];

但它返回未定义。当我执行 console.log(array) 时,我得到以下信息:

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

ETC...

如何使用上述语法获取第二项的值?

谢谢!

这是完整的代码:

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'
4

1 回答 1

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]);
}
于 2013-10-09T15:39:38.810 回答