[英]Javascript - Question regarding Set Timeout
As per my understanding, the below function should print 5 five times because of hoisting .据我了解,下面的 function 应该打印5 5 次,因为吊装。 But instead, it prints 6 five times .但相反,它打印了6 五次。
Question is, how come it prints 6 when the loop's limit is <=5
?问题是,当循环的限制为<=5
时,它怎么会打印6 ?
function () {
for ( var i = 1; i <= 5; i++) {
setTimeout( function() {
console.log(i); // 👈 this should print '5' five times
}, i * 1000)
}
}
It prints 6 because that's the value of i
when the loop exits.它打印 6 因为这是循环退出时i
的值。
Consider the flow at the end of the loop's run, when i
is 4:考虑循环运行结束时的流程,当i
为 4 时:
The for loop stops after the i++
occurs which meets the condition for exiting (ie 6 > 5
) - at that point, the value of i
has incremented to 6
already and about a second later the value of i
is printed在满足退出条件的i++
发生后 for 循环停止(即6 > 5
) - 此时, i
的值已经增加到6
并且大约一秒钟后i
的值被打印
It is because of the increment you apply sol =>这是因为您应用的增量 sol =>
function num() {
for ( var i = 1; i <= 4; i++) {
setTimeout( function() {
console.log(i); // 👈 this should print '5' five times
}, i * 1000)
}
}
num()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.