for ( var d = 0; d < 3; d++ )
(function(d)
{
setTimeout(
function()
{
console.log( "Value of d: ", d );
console.log( d == d, "Check the value of d." );
}, d * 200);
})(d);
时间参数(d)如何工作?在for循环内使用setTimeout。在for循环中使用SetTimeout的困惑。
该代码似乎可以正常工作。
但如果你比较想了解它,你可以最终拿起JS的进口贸易..瓶盖
所以先这样运行
for ( var d = 0; d < 3; d++ )
setTimeout(function() {
console.log( "Value of d: ", d );
console.log( d == d, "Check the value of d." );
}, d * 200);
输出 :
Value of d: 3
true "Check the value of d."
Value of d: 3
true "Check the value of d."
Value of d: 3
true "Check the value of d."
您是否注意到的非增量值d
?这是因为在d
实际执行任何setTimeout函数之前,值变为3。因此,您需要的是d
值1,2,3的三个副本。
这可以通过执行立即函数并d
在定义setTimeout函数本身时保存其值来实现。我们本质上所做的就是将每个调用包装在一个范围内,该范围d
以后可以访问(在setTimeout函数启动之后)。
因此,您的代码:
for ( var d = 0; d < 3; d++ ) (function(d) {
setTimeout(function() {
console.log( "Value of d: ", d );
console.log( d == d, "Check the value of d." );
}, d * 200);
})(d);
产生输出:
Value of d: 0
true "Check the value of d."
Value of d: 1
true "Check the value of d."
Value of d: 2
true "Check the value of d."
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句