简体   繁体   中英

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; with currentLocation++; , it works as intended. Just curious as to why this happens.

currentLocation starts out at 1.

In the loop:

On the first pass, it adds 0 to currentLocation , leaving it at 1.

On the second pass, it adds 1 to currentLocation making it 2.

On the third pass, it adds 2 to currentLocation , making it 4.

On the fourth pass, it adds 3 to currentLocation , making it 7.

On the fifth pass, it adds 4 to currentLocation , making it 11.

And so on.

As you can see, it's always !== 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.

It is because currentLocation never becomes equal to 9.

Iteration 1:

i = 0
currentLocation = 1 
1 + 0 = 1 

Iteration 2:

i = 1
currentLocation = 1 
1 + 1 = 2 

Iteration 2:

i = 2
currentLocation = 2 
2 + 2 = 4 

Iteration 3:

i = 3
currentLocation = 4 
3 + 4 = 7

Iteration 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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