我使用数组来存储Google地理编码API的格式化结果。在函数调用之后,我使用console.log查看数组的内容,它正常工作,但是当我尝试访问单个元素时,它返回" undefined"。当我检查数组长度时,我得到零。这是我的代码(addressInput是一个存储三个地址的对象):
function startGeocode(addressInput) {
var addressOut = [];
var outString = "";
var address = "";
for(var i = 0; i < addressInput.length; i++) {
address = addressInput[i].address + " " + addressInput[i].city + " " + addressInput[i].state + " " + addressInput[i].zip;
geocoder.geocode({'address':address}, function(results,status) {
if(status == 'OK') {
outString = "" + results[0].geometry.location;
outString = outString.replace(/\(|\)|\s/g,'');
outString = outString.replace(/\,/g,' ');
addressOut.push(outString);
} else {
outString = "Error: " + status;
addressOut.push(outString);
}
});
}
console.log(addressOut);
console.log(addressOut[0]);
console.log(addressOut.length);
}
三个console.log调用返回以下内容:
/* (Using a codeblock for readability)
Array[0]
0:"(a correctly formatted latitude and longitude)"
1:"(a correctly formatted latitude and longitude)"
2:"(a correctly formatted latitude and longitude)"
addressOut[0]: undefined
addressOut.length: 0
*/
所以我的问题是,为什么我的数组长度为零,为什么我无法引用数组的元素?
答案 0 :(得分:3)
因为您正在使用异步函数geocoder.geocode
。这意味着您在此功能完成之前打印到console var。使用回调或承诺。