JavaScript变量绑定和循环 [英] JavaScript variable binding and loop

查看:104
本文介绍了JavaScript变量绑定和循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这样的循环:

  for(var it = 0; it< 2; it ++)
{
setTimeout(function(){
alert(it);
},1);
}

输出是:

  => 2 
=> 2



我希望它是:0,我看到两种方法来修复它: / p>

解决方案#1。



这是基于我们可以将数据传递给setTimeout的事实。

  for(var it = 0; it< 2; it ++)
{
setTimeout {
alert(data);
},1,it);
}

解决方案2。

  function foo(data)
{
setTimeout(function(){
alert(data);
},1);
}

for(var it = 0; it< 2; it ++)
{
foo(it);
}

是否还有其他替代品?

 

code> for(var it = 0; it< 2; it ++)
{
(function(){
var m = it;
setTimeout ){
alert(m);
},1);
})();
}

基本上,你需要捕获一个闭包中的变量值。此方法使用立即调用的匿名函数捕获局部变量 m 中的外部变量值 it



以下是 工作演示 玩。请在网址中添加 / edit 以查看代码


Consider such loop:

for(var it = 0; it < 2; it++)
{
    setTimeout(function() {
        alert(it);
    }, 1);
}

The output is:

=> 2
=> 2

I would like it to be: 0, 1. I see two ways to fix it:

Solution # 1.

This one based on the fact that we can pass data to setTimeout.

for(var it = 0; it < 2; it++)
{
    setTimeout(function(data) {
        alert(data);
    }, 1, it);
}

Solution # 2.

function foo(data)
{
    setTimeout(function() {
        alert(data);
    }, 1);
}

for(var it = 0; it < 2; it++)
{
    foo(it);
}

Are there any other alternatives?

解决方案

Not really anything more than the two ways that you have proposed, but here's another

for(var it = 0; it < 2; it++)
{
    (function() {
        var m = it;   
        setTimeout(function() {
            alert(m);
        }, 1);
    })(); 
}

Essentially, you need to capture the variable value in a closure. This method uses an immediately invoked anonymous function to capture the outer variable value it in a local variable m.

Here's a Working Demo to play with. add /edit to the URL to see the code

这篇关于JavaScript变量绑定和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆