简体   繁体   English

Javascript全局变量仅在匿名函数内更新

[英]Javascript Global variable only update inside anonymous function

please give me some clue for this javascript problem. 请给我一些线索来解决这个javascript问题。 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. 你正在推动使用setTimeout调用的函数中的markers ,因此推迟直到一段时间后才会发生。 But you're calling alert(markers) immediately, before any of the timeouts have occurred. 但是,在发生任何超时之前,您会立即呼叫alert(markers) So the array is empty at that time. 所以那时数组是空的。

UPDATE: 更新:

To see the final contents of markers , you need another setTimeout : 要查看markers的最终内容,您需要另一个setTimeout

setTimeout(function() { alert(markers); }, netotal*50);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM