最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

stuck with Javascript infinite while loop - Stack Overflow

programmeradmin2浏览0评论

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

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

How e 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!

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

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

How e 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!

Share Improve this question asked Aug 9, 2013 at 23:18 PatpadsPatpads 31 silver badge2 bronze badges 2
  • 5 Consider using a linter like jshint. to help you find mon mistakes. It would have told you "Expected a conditional expression and instead saw an assignment.". – user2437417 Commented Aug 9, 2013 at 23:27
  • Wow thanks everyone so much for the warm wele with my 1st question. My new family is here :D Can't believe I mixed up the operands... @CrazyTrain: thanks for sharing! – Patpads Commented Aug 10, 2013 at 0:33
Add a ment  | 

5 Answers 5

Reset to default 4

You're doing an assignment instead of a parison.

Change:

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

to:

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

Use == instead of = in the while part.

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/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/nabil_kadimi/pdV4M/):

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

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 want to use the === parison operator instead of the = assignment operator in the while loop.

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

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

评论列表(0)

  1. 暂无评论