对于JavaScript中的循环,只输出上次迭代的值 [英] For Loop in Javascript outputs value only from last iteration

查看:115
本文介绍了对于JavaScript中的循环,只输出上次迭代的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < div class =test>< p class = / DIV> 

< script>
setTimeout(function(){$(。test)。append(test1)},1000);
setTimeout(function(){$(。test)。append(test2)},2000);
< / script>
< script src =js / jquery.min.js>< / script>

先显示test1,稍后显示test2,例如:test1test2 ,这是我想要的。



当我尝试在FOR循环中执行此操作时,像这样:

  var timeInterval = 1000; 
for(var i = 0,l = 2; i setTimeout(function(){$(。test)。append(test+ i)} ,时间间隔);
timeInterval + = 1000;
}

然后,我先得到test2,稍后再得到test2因为这样:test2test2,这是不是我想要的。

实际上,如果l = 3,那么我得到test3test3test3,而不是test1test2test3。是否有人知道如何解决这个问题?

解决方案

var i setTimeout 正在执行该函数时,它会增加到2,因此它只是将 i 值打印为2, code> test2test2 。



您应该使用闭包来使用 i ,它将打印 test1test

DEMO: http: // $ jsfiddle.net/mBBJn/1/

  var timeInterval = 1000; (函数()(){
$(函数($ i
$函数(i) .test)。append(test+(i + 1))
},timeInterval);
timeInterval + = 1000;
})(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中的循环,只输出上次迭代的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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