Javascript中的For循环仅输出上次迭代的值 [英] For Loop in Javascript outputs value only from last iteration
问题描述
我有这个 Javascript 代码,它按预期工作:
<脚本>setTimeout(function(){$(".test").append("test1")},1000);setTimeout(function(){$(".test").append("test2")},2000);<script src="js/jquery.min.js"></script>
它先显示test1",然后再显示test2",例如:test1test2",这正是我想要的.
当我尝试在 FOR 循环中执行此操作时,如下所示:
var timeInterval = 1000;for (var i = 0, l = 2; i
然后我先得到test2",然后再得到test2",例如:test2test2",这不是我想要的.
事实上,如果 l = 3,那么我得到的是test3test3test3"而不是test1test2test3".有人知道如何解决这个问题吗?
当 setTimeout
正在执行函数时,var i
增加到 2,所以它只是打印i
值为 2,结果为 test2test2
.
您应该使用闭包来使用 i
的实例,它将打印 test1test
.
演示: http://jsfiddle.net/mBBJn/1/一个>
var timeInterval = 1000;for (var i = 0, l = 2; i
使用了函数参数.
I have this Javascript code, which works as expected:
<div class="test"></div>
<script>
setTimeout(function(){$(".test").append("test1")},1000);
setTimeout(function(){$(".test").append("test2")},2000);
</script>
<script src="js/jquery.min.js"></script>
It shows "test1" first and then "test2" a second later, as such: "test1test2", which is what I want.
When I try to do this in a FOR loop, like this:
var timeInterval = 1000;
for (var i = 0, l = 2; i < l; i++ ) {
setTimeout(function(){$(".test").append("test" + i)},timeInterval);
timeInterval += 1000;
}
Then I get "test2" first and then "test2" a second later, as such: "test2test2", which is not what I want.
In fact, if l = 3, then I get "test3test3test3" instead of "test1test2test3". Does anybody know how to solve this problem?
The var i
is incremented to 2 when the setTimeout
is executing the function and so it just prints the i
value as 2 resulting in test2test2
.
You should use a closure to use the instance of i
which will print test1test
.
DEMO: http://jsfiddle.net/mBBJn/1/
var timeInterval = 1000;
for (var i = 0, l = 2; i < l; i++) {
(function(i) {
setTimeout(function() {
$(".test").append("test" + (i+1))
}, timeInterval);
timeInterval += 1000;
})(i);
}
Edit: used function args.
这篇关于Javascript中的For循环仅输出上次迭代的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!