Sha*_*har -2 javascript increment while-loop
为什么以下逻辑不起作用?
警告:当您单击"运行代码段"时,以下内容将启动无限循环.
var i = 0;
var currentLocation = 1;
while(currentLocation !== 9){
console.log(currentLocation);
currentLocation += i;
i++;
}Run Code Online (Sandbox Code Playgroud)
这进入了一个无限循环.但是如果我们替换currentLocation += i;它currentLocation++;,它按预期工作.只是好奇为什么会这样.
currentLocation 从1开始.
在循环:
在第一次传递时,它将0添加到currentLocation,将其保留为1.
在第二遍,它增加1 currentLocation使其成为2.
在第三遍,它增加2 currentLocation,使其为4.
在第四遍,它增加3 currentLocation,使其成为7.
在第五遍,它增加了4 currentLocation,使其成为11.
等等.
如你所见,它总是如此!== 9.
通过在浏览器和/或IDE中内置的调试器中逐步执行代码语句,随时观察变量的值,可以最好地理解这种情况.