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

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

问题描述

考虑这样的循环:

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

输出为:

=> 2
=> 2

我希望它是:0、1.我看到了两种修复方法:

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

解决方案#1.

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

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);
}

解决方案#2.

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

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

还有其他选择吗?

推荐答案

实际上只是您提出的两种方式,但这是另一种方式

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);
    })(); 
}

本质上,您需要在闭包中捕获变量值.此方法使用立即调用的匿名函数来捕获局部变量 m 中的外部变量值 it.

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.

这里有一个 工作演示 可以玩.将 /edit 添加到 URL 以查看代码

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

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

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