0
我一直在搜索SE好2個小時,試圖解決我失去「位置」變量值的原因。利用閉包看起來像是最好的解決方案,但在下面的回調函數中,我無法弄清楚如何正確實現它。JavaScript/GoogleMaps/Geocode - for循環內的回調函數內未設置的變量
有人可以藉此瞭解一下這種現象究竟如何完全可以糾正?如果有任何關鍵術語,請將它們指出來,以便我可以相應地進行研究。
謝謝你的時間。
有問題的代碼:
for (var i = 0; i < locations.length; i++) {
geocoder.geocode({
'address': locations[i] // Returns location as expected
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(locations[i]); // returns undefined
}
})
}
爲了澄清,我已經看到了類似這樣的一個最接近的崗位:When using callbacks inside a loop in javascript, is there any way to save a variable that's updated in the loop for use in the callback?,但我無法使它的情況範圍內工作。
再次感謝。
注意添加關於JavaScript的範圍的一些信息? :P – laconbass
@laconbass通過它像一個對象,更新的代碼,現在alert(locObj)輸出什麼? – Rustam
@laconbass你知道我認爲也有位置變量,它覆蓋你的位置變量,那是因爲它的未定義,所以使用一個對象來傳遞數據,就像我上面的代碼 – Rustam