我试图创建一个 for 循环,递增数字 1 - 4 并打印它们,但是当我在循环后打印 i 的值时,我的代码输出 5。
for (i = 1; i < 5; i++) {
document.write(i + "<br>"); //Outputs numbers 1 - 4
}
document.write("New i: " + i); //Outputs 5
如果我只能递增直到其值为 4,这怎么可能?
当您在循环语句中声明变量时,它将将该变量存储在与循环相同的范围内。循环在循环结束时递增 (i++),然后检查条件 (i
另外,在声明 i 时应该使用 var 关键字,否则该变量将存储在全局范围中(这是不好的做法)。
//variable i is captured here (with the var keyword)
for(var i = 1; i < 5; i++) {
//for the fourth iteration, i === 4
//so it prints 4.
document.write(i);
//i++ happens right now, so i now is 5.
//then the loop checks the condition to see if it
//should continue. i isn't less than 5, so the loop breaks.
}
//and the value of i is still 5. so this prints 5.
document.write('</br>' + i);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)