javascript for循环意外行为 [英] javascript for loop unexpected behaviour

查看:126
本文介绍了javascript for循环意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个关于javascript for循环的问题。

I have couple of questions about the javascript for loop.

第一个问题:

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

输出为3.不应该是2吗?

Output is 3. Shouldn't it be 2?

第二个问题:

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

超时设置正确:0,1000和2000.但输出为3 ,3,3(应为0,1,2)。这是否意味着在循环退出后执行延迟函数?为什么?

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?

我应该阅读什么才能理解所有这些神秘的javascript内容?

What should I read to understand all this mysterious javascript stuff?

谢谢。

推荐答案

第一个问题:

否,因为<$ <$ em>> 变量在最后一次成功迭代后递增,然后检查条件并将其计算为 false 所以循环结束。

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 composed by:

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

并按以下步骤执行:


  1. initialExpression 在开始时进行评估

  2. 评估条件,如果它的计算结果为 false ,循环结束,如果计算结果为 true ,则评估该语句。

  3. 评估声明。

  4. incrementExpress评估离子,转到第2步。

  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.

第二个问题:

该函数在循环结束后异步执行,此时您知道 i 包含 3

此常见的解决方法是使用函数来保留循环的值每次迭代的变量,例如:

The common 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);
}

这篇关于javascript for循环意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆