在 for 循环中将参数传递给 setTimeout [英] Passing argument to setTimeout in a for loop

查看:38
本文介绍了在 for 循环中将参数传递给 setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何在 javacript for 循环中将参数传递给 setTimeout.这是示例代码.正如目前所写,setTimeout 每次传递的都是相同的 i,而不是反映数组中实际存在的不同 i.

I'm trying to learn how to pass an argument to setTimeout in a javacript for loop. Here is the example code. As it is currently written, setTimeout is passed the same exact i each time, not reflecting the different i's that are actually in the array.

var a=100;
for (i in array)
{   
    setTimeout("do_stuff(i, a)"), 2000);    
}

(我在这里看到了一些类似的问题和答案,但代码示例要复杂得多.回答这个最基本的示例可以帮助其他人解决同样的问题.谢谢!!!)

(I've seen somewhat similar questions and answers here, but the code examples are much more complicated. Answering this most basic example could much help others with the same problem. Thanks!!!)

推荐答案

要使用字符串(你不应该这样做),你需要这样做:

To use a string (which you shouldn't do), you 'd need to do this:

var a=100;
for (i in array)
{   
    setTimeout("do_stuff(" + i + ", a)"), 2000);    
}

更好的答案是在新函数调用中定义 i 变量的范围,它返回一个匿名函数以提供给 setTimeout().

A better answer would be to scope the i variable in a new function invocation, which returns an anonymous function to give to setTimeout().

function do_stuff( i, a ) {
    return function() {
        // do something with i and a
    }
}

var a=100;
for (i in array)
{   
    setTimeout(do_stuff( i , a ), 2000);    
}

现在 do_stuff() 返回一个函数,该函数具有对新 ia 变量的作用域引用.由于对 do_stuff 的每次调用都有自己的作用域,因此您返回的函数将引用正确的值.

Now do_stuff() returns a function that has a scoped reference to a new i and a variable. Because each call to do_stuff will have its own scope, the function you return will reference the correct values.

题外话,但如果array实际上是一个Array,那么你真的不应该使用for-in 因为它用于枚举.对于数组,您通常需要对数字索引进行迭代,因此应该使用标准的 for 循环.

Off topic, but if array is actually an Array, then you really shouldn't use for-in because that's meant for enumeration. With an Array, you typically want iteration of numeric indices, and as such should use a standard for loop.

这篇关于在 for 循环中将参数传递给 setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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