我在循環中反覆調用google api函數。 每次我想刪除地址數組中的一個元素。javascript - google地理編碼 - 關閉/循環問題
for(var i = 0; i < AddressObject.addressToArray.length; i++){
srPerformGeocode(AddressObject);
console.log(AddressObject.addressToArray);
AddressObject.addressToArray.splice(0, 1);
}
// --------------------------------------------------------------
// Perform geocoding
// --------------------------------------------------------------
function srPerformGeocode(AddressObject)
{
address = AddressObject.addressToArray.join(",");
console.log(AddressObject.addressToArray);
if (geocoder){
geocoder.geocode({'address': address.trim() }, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK){
console.log("geocoded " + AddressObject.addressToArray);
// Do something
}
else{
alert("FAIL");
}
});
}
}
這似乎是發生的是,循環運行我的時間, 和功能srPerformGeocode運行每次我使用時間的 我循環的最後一個值。
['field1' ,'field2' ,'field3' ,'field4' ]
['field1' ,'field2' ,'field3' ]
['field1' ,'field2' ]
['field1' ]
geocoded field1
geocoded field1
geocoded field1
geocoded field1
[Javascript閉合內部循環 - 簡單實用示例]的可能重複(http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – rds 2013-01-17 17:56:22