传递参数的setTimeout在for循环 [英] Passing argument to setTimeout in a for loop
问题描述
我想学习如何将参数传递给setTimeout的在for循环javacript。这里是例如code。由于它目前正在写的,setTimeout的传递完全一样的我,每次,不是反映了不同的我的,实际上是在数组中
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);
}
(我见过有些类似的问题和答案在这里,但在code例子要复杂得多。要回答这个最基本的例子可以多帮助其他有同样的问题。谢谢!)
(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()
的返回的,有一个范围的引用到一个新的函数I
和 A
变量。因为每次调用 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.
编辑: 题外话,但是,如果阵列
实际上是一个阵列
,那么你真的不应该使用换的
因为这是意味着枚举。随着一个数组,你通常需要的迭代数字索引的,因此应使用标准为
循环。的
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.
这篇关于传递参数的setTimeout在for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!