Javascript,For 循环:返回的 'i' 值与存储的值不同

Javascript, For loop: returned 'i' value is different from that is stored

在此循环中,alert(i) 提醒 12,firebug 显示 10 作为最终结果。

 for(var i=0;i<=10;i=i+2){
      document.write=i;
    }

    alert(i);

i 在每次循环迭代后递增。当条件 <= 10 失败时,循环中断:

0 => loop gets executed, i incremented with 2
2 => loop gets executed, i incremented with 2
4 => loop gets executed, i incremented with 2
6 => loop gets executed, i incremented with 2
8 => loop gets executed, i incremented with 2
10 => loop gets executed, i incremented with 2
12 => loop breaks => i remains at 12

但这是正确的。

开始i=0,然后我们迭代并在每个循环中添加 2。

当我们到达 10 时,我们仍然在条件内,所以我们再做一个循环。现在是 i==12,但是这个条件会告诉我们跳出循环。

所以刹车出环后i==12.

将其视为代码:

i==0 //inside loop
i==2 //inside loop
i==4 //inside loop
i==6 //inside loop
i==8 //inside loop
i==10 //inside loop - we will add 2 once more time
i==12 //we are outside the loop, because now i>10

您的 for 循环以 2 为增量递增。

0 2个 4个 6个 8个 10
12

10 仍然是 'less than OR equal to 10',因此 for 循环继续 运行 一次,直到到达 12,此时条件不再为真。

将您的代码更改为

for(var i=0;i<10;i=i+2){
  document.write=i;
}

alert(i);