I have couple of questions about the javascript for loop.
First question:
for (i=0; i<=2; i++) {;}
console.log(i);
Output is 3. Shouldn't it be 2?
Second question:
for (var i=0; i<=2; i++) {
setTimeout(function(){console.log(i);}, i*1000);
}
Timeouts are set correctly: 0, 1000 and 2000. But the output is 3,3,3 (should be 0, 1, 2). Does this mean the delayed functions are executed after the loop exits? Why?
What should I read to understand all this mysterious javascript stuff?
Thank you.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…