最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript for loop unexpected behaviour - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Jul 3, 2010 at 6:50 mgsmgs 2,6892 gold badges19 silver badges15 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 11

First question:

No because the i variable is incremented after the last successful iteration, then the condition is checked and it evaluates to false so the loop ends.

The for statement is posed by:

for ([initialExpression]; [condition]; [incrementExpression])
  statement

And it is executed in the following steps:

  1. The initialExpression is evaluated at the start
  2. The condition is evaluated, if it evaluates to false, the loop ends, if it evaluates to true, the statement is evaluated.
  3. Evaluate the statement.
  4. The incrementExpression is evaluated, go to step 2.

Second question:

The function is executed asynchronously after the loop has ended, at this time as you know i contains 3.

The mon workaround for this is to use a function to preserve the value of the looping variable on each iteration, for example:

for (var i=0; i<=2; i++) {
  (function (i) {
    setTimeout(function(){console.log(i);}, i*1000);
  })(i);
}

That's because your console.log instruction is outside of the for loop.

This will print it up to two as you intended:

for (i=0; i<=2; i++) {
    console.log(i);
}

For loops will only repeatedly execute what you type within the parentheses. That's why console.log was executed only once.

Source: http://www.kompulsa./a-guide-to-for-loops-in-javascript/

发布评论

评论列表(0)

  1. 暂无评论