2016-12-05 78 views
-1

我正在使用數組來存儲來自Google地理編碼API的格式化結果。在函數調用之後,我使用console.log來查看數組的內容,該數組工作正常,但是當我嘗試訪問單個元素時,它返回「undefined」。當我檢查數組長度時,我得到零。這裏是我的代碼(addressInput是存儲三個地址的對象):Javascript全局數組返回undefined

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 
*/ 

所以我的問題是,爲什麼我得到一個數組的長度爲零,爲什麼我不能引用數組的元素?

回答

2

因爲您正在使用異步功能geocoder.geocode。這意味着在此函數完成之前,您正在打印到控制檯var。使用回調或承諾。

+0

也許這個原因錯誤 – Mahi