这是我的示例代码
var selected_path = [];
for (var i = 0; i <path.length-1; i++) {
var request = {
origin: path[i],
destination: path[i+1],
travelMode: google.maps.DirectionsTravelMode.WALKING
}
directionsService.route(request, function(results, status) {
if (status == google.maps.DirectionsStatus.OK) {
selected_path = selected_path.concat(results.routes[0].overview_path);
}
})
}
console.log(selected_path); // slected_path in console is []
poly.setPath(selected_path);
poly.setMap(map);
在这种情况下,控制台中的 selected_path 是 []。当我在 console.log(selected_path) 之前添加 alert(i) 行时。添加后的代码如下:
var selected_path = [];
for (var i = 0; i <path.length-1; i++) {
var request = {
origin: path[i],
destination: path[i+1],
travelMode: google.maps.DirectionsTravelMode.WALKING
}
directionsService.route(request, function(results, status) {
if (status == google.maps.DirectionsStatus.OK) {
selected_path = selected_path.concat(results.routes[0].overview_path);
}
})
}
alert(i) ////// ADDED ONE LINE
console.log(selected_path); /// selected_path in console has proper value
poly.setPath(selected_path);
poly.setMap(map);
变量 i 在屏幕上显示为警报,变量 selected_path 具有适当的值。谁能给我解释一下,因为我不明白。为了澄清它在 Firefox 中有效,可能不适用于 chrome。