简体   繁体   English

JavaScript While 循环条件变量未更新

[英]JavaScript While loop condition variable not getting updated

Why does the following logic not work?为什么下面的逻辑不起作用?

Warning : The following starts an infinite loop when ou click Run code snippet.警告:当您单击运行代码片段时,以下内容将启动无限循环。

 var i = 0; var currentLocation = 1; while(currentLocation !== 9){ console.log(currentLocation); currentLocation += i; i++; }

This goes into an infinite loop.这就进入了一个无限循环。 But if we replace currentLocation += i;但是如果我们替换currentLocation += i; with currentLocation++;与当前位置currentLocation++; , it works as intended. ,它按预期工作。 Just curious as to why this happens.只是好奇为什么会发生这种情况。

currentLocation starts out at 1. currentLocation从 1 开始。

In the loop:在循环:

On the first pass, it adds 0 to currentLocation , leaving it at 1.在第一遍时,它将 0 添加到currentLocation ,使其保持在 1。

On the second pass, it adds 1 to currentLocation making it 2.在第二遍时,它将currentLocation 1,使其变为 2。

On the third pass, it adds 2 to currentLocation , making it 4.在第三遍时,它会将 2 添加到currentLocation ,使其成为 4。

On the fourth pass, it adds 3 to currentLocation , making it 7.在第四次传递时,它会将 3 添加到currentLocation ,使其成为 7。

On the fifth pass, it adds 4 to currentLocation , making it 11.在第五遍时,它将currentLocation 4,使其为 11。

And so on.等等。

As you can see, it's always !== 9 .正如你所看到的,它总是!== 9


This is the kind of thing that's best understood by stepping through the code statement by statement in the debugger built into your browser and/or IDE, watching the values of the variables as you go.最好通过在浏览器和/或 IDE 中内置的调试器中逐句逐句执行代码,并在执行过程中观察变量的值来最好地理解这种情况。

It is because currentLocation never becomes equal to 9.这是因为currentLocation永远不会等于 9。

Iteration 1:迭代 1:

i = 0
currentLocation = 1 
1 + 0 = 1 

Iteration 2:迭代 2:

i = 1
currentLocation = 1 
1 + 1 = 2 

Iteration 2:迭代 2:

i = 2
currentLocation = 2 
2 + 2 = 4 

Iteration 3:迭代 3:

i = 3
currentLocation = 4 
3 + 4 = 7

Iteration 4:迭代 4:

i = 4
currentLocation = 7 
7 + 4 = 11 // MORE than 9

Step through the process.逐步完成该过程。

when you start你几时开始

i = 0, currentLocation = 1

when you go through the first iteration当你进行第一次迭代时

i = 1, currenttLocation = 1

when you go through the second iteration当你进行第二次迭代时

i = 2, currentLocation = 2

on the third在第三

i = 3, currentLocation = 4

on the fourth在第四

i = 4 currentLocation = 7

on the fifth在第五

i = 5 currentLocation = 11

since currentLocation will never exactly equal 9, the loop will never break因为 currentLocation 永远不会完全等于 9,所以循环永远不会中断

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM