简体   繁体   English

JavaScript无法读取function()中的变量

[英]Javascript can't read variable in function()

I have an example on this code: 我有一个关于此代码的示例:

<script>
    for(var i=1; i<3; i++){
        setTimeout(function(){
            say("HELLO NUMBER " + i);
        }, i * 2000);
    }

    function say(text){
        alert(text);
    }
</script>

And output I need is : 我需要的输出是:

alert("HELLO NUMBER 1"); alert(“ HELLO NUMBER 1”);

alert("HELLO NUMBER 2"); alert(“ HELLO NUMBER 2”);

But in this case, I still get output : 但是在这种情况下,我仍然得到输出:

alert("HELLO NUMBER 3"); alert(“ HELLO NUMBER 3”);

Anyone can help for this? 有人可以帮忙吗? thanks :) 谢谢 :)

Classic problem with closure 封闭的经典问题

for(var i=1; i<=3; i++){
    (function(num){
        setTimeout(function(){
            say("HELLO NUMBER " + num);
        }, num * 2000);

    })(i)
}

function say(text){
    alert(text);
}

Demo: Fiddle 演示: 小提琴

You are using a closure variable i inside the setTimeout callback, whose value is evaluated only when the callback is executed by then the value of i will be updated by the outside loop 您在setTimeout回调中使用了闭合变量i ,仅在执行回调时才评估其值,然后i的值将由外部循环更新

Another way. 其他方式。

var out = [];
for(var i=0; i<3; ++i){
    out.push(i+1);
    setTimeout(function(){
        say("HELLO NUMBER " + out.shift());
    }, i * 2000);
}

function say(text){
    alert(text);
}

you need a closure for the value of i for each iteration: 您需要为每个迭代的i值封闭:

for (var i=1; i<3; i++) {
    (function(j){
        setTimeout(function() { alert("HELLO NUMBER " + j); }, j*2000);
    })(i)
}
<script>
    function doSetTimeout(i) {
         setTimeout(function() { say("HELLO NUMBER " + i); }, 3000);
    }

    for(var i=1; i<3; i++){
        doSetTimeout(i);
    }

    function say(text){
    alert(text);
   }
</script>

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

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