please give me some clue for this javascript problem. I have a global variable markers. And try to push every marker to markers. But the problem is , after push to markers. i was trying to alert the value inside function and outside function. the result is totally different. markers inside function give me array of marker, but markers outside stay empty. Why i got different value of markers global variable?
This is the snippet of my code:
for (var i = 0; i < netotal; i++) {
setTimeout(function () {
marker = new google.maps.Marker({
position: pos[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
icon: neicon
});
iterator++;
markers.push(marker);console.log(markers);
}, i * 50);
}
alert (markers);
Thank you for your kind help or clue.
取决于范围,访问全局标记使用window.markers
。
You're pushing to markers
in a function that's called using setTimeout
, so the push won't happen until some time later. But you're calling alert(markers)
immediately, before any of the timeouts have occurred. So the array is empty at that time.
UPDATE:
To see the final contents of markers
, you need another setTimeout
:
setTimeout(function() { alert(markers); }, netotal*50);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.