最佳答案
This code logs 6
, 6 times:
(function timer() {
for (var i=0; i<=5; i++) {
setTimeout(function clog() {console.log(i)}, i*1000);
}
})();
But this code...
(function timer() {
for (let i=0; i<=5; i++) {
setTimeout(function clog() {console.log(i)}, i*1000);
}
})();
... logs the following result:
0
1
2
3
4
5
Why?
Is it because let
binds to the inner scope each item differently and var
keeps the latest value of i
?