undefinedfix
Sign in

Ask a question about JS

qcrat edited in Tue, 22 Dec 2020
for(var i=0; i<5; i++) {
    setTimeout(function() {
        console.info(i);
    }, 0);
}
console.info(i);  // 这里为什么输出的是5
9 Replies
hardbidouille
commented on Tue, 22 Dec 2020

http://www.qdfuns.com/notes/1... This is explained in detail

user3413026
commented on Tue, 22 Dec 2020

The VaR declarator is the function scope. Although I was declared in the for loop, VAR has a declaration promoted to the top of the function, so I can also be accessed under for. ES6 has new const and let declarators, which are block scopes.

NWMFRBoulder
commented on Wed, 23 Dec 2020

Var declares a global variable. Although you declare I in the code block of the for loop, it is a global variable. When the print logic is executed, I has become 5. Let is used to declare local variables.

user617398
commented on Wed, 23 Dec 2020

If you just don't understand why you enter 5, it should be simpler. This is just related to JS scope. thank you!

user1300830
commented on Wed, 23 Dec 2020

Before JS ES6, there was no block level scope concept. The VaR scope is the execution environment of the global or function where your morphology is located.

jdrover
commented on Wed, 23 Dec 2020

In JS (Es5), variables declared by VAR have no block level scope. In ES6, let declaration can be used to solve this problem.

for(var i=0; i<5; i++) {
    setTimeout(function() {
        console.info(i);
    }, 0);
}
console.info(i); 

to

(function (){
    for(var i=0; i<5; i++) {
        setTimeout(function() {
            console.info(i);
        }, 0);
    }
})();
console.info(i);  // undefined
NWFortCollinsCO
commented on Wed, 23 Dec 2020

The article I wrote two days ago just analyzes this

https://segmentfault.com/a/11...

Post it, run down and try it yourself, and analyze it according to the examples. I hope I can help you.

nickhardiman
commented on Wed, 23 Dec 2020

The reason for the delay of timer execution

Amer
commented on Wed, 23 Dec 2020

SetTimeout is a queue function. It will wait until other functions and statements in the same scope are executed. So when the timer is on, the for loop is over, and I is always 5.

lock This question has been locked and the reply function has been disabled.