我正面臨一些愚蠢的問題,我知道我錯過了一些東西。簡單數組長度 - 總是0即使內容存在
我有一個空白數組,其中我使用.push()方法推動的東西。
現在當我打印完整的數組時,我得到了值,但是當我使用array.length時,它總是爲零。我知道這是我很想念的東西,非常愚蠢。
var markersToPush = [];
for (var i = 0; i < contactList.length; i++) {
console.log('conatcat addres', contactList[i].MailingStreet);
geocoder.geocode({
'address': contactList[i].MailingStreet
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markersToPush.push(marker.getPosition());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
console.log('markers to push-->', markersToPush);
console.log('markers length-->', markersToPush.length);
對於結果的日誌 -
我已經檢查等相互關聯的問題 -
- Javascript array returns length as 0 always even there are elements in it
- Javascript array returns length as 0 always even there are elements in it
- Array Length returns 0
請將您的代碼*在這裏* – Li357
添加相關代碼部分 –
請將代碼作爲文本發佈,而不是代碼圖片。無論如何,我想你會發現在你登錄的時候數組是空的,但是當你在控制檯中展開數據時,它會有數據。 (如果你記錄'JSON.stringify(markersToPush)',它會確認它)。你正在調用一個異步函數'geocoder.geocode()',並且你傳遞給它的回調函數將不會被數據調用在循環結束後並在'console.log()'語句之後。看到[這個問題](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)。 – nnnnnn