简体   繁体   中英

stuck with Javascript infinite while loop

My apologies for the n00b question, I've tried looking through infinite loop related issues but they're way more complex:

var replay = 1;
while (replay = 1) {
replay = prompt("Yes(1) or No(0) ?");
}

How come this is an infinite loop?

I thought this while loop would only continue iterating while the replay variable has a value of 1.

However it doesn't stop even when user input is 0, or anything else for that matter.

Thanks in advance for any of your input!

You're doing an assignment instead of a comparison.

Change:

while (replay = 1) { // Will always have a value of 1

to:

while (replay == 1) { // Will have a value of true or false

在while部分中使用==代替=

You need to use == (equality) instead of = (assignment) in your while loop

while(replay == 1) {
  //code
 }

JavaScript is doing what it is supposed to. You are reassigning the value of 1 to replay every time the loop iterates. You really want to check if replay is equal to one before proceeding.

You are assigning not checking in (replay = 1)

You need double equal signs == , or better yet triple equal signs === which will also check the equality in types of the operands.

Besides, your code can be changed to this (preview: http://jsfiddle.net/nabil_kadimi/RfdA5/ ):

var replay;
while ((replay = window.prompt("Yes(1) or No(0) ?")) === '1') {
  /* player wants to replay */;
}

Or even better (preview: http://jsfiddle.net/nabil_kadimi/pdV4M/ ):

var replay;
while (replay = window.confirm("Replay?")) {
  /* player wants to replay */;
}

You want to use the === comparison operator instead of the = assignment operator in the while loop.

Also, since prompt returns a string , you should compare against a string :

var replay = "1";
while (replay === "1") {
  replay = prompt("Yes(1) or No(0) ?");
}

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