简体   繁体   中英

Can't get out of my while loop (Javascript)

as a first project after doing the code-academy course I'm making a rock/paper/scissors game but I can't see where I'm going wrong with my loop here.

while (userChoice !== "ROCK" | "PAPER" | "SCISSORS" | "LIZARD" | "SPOCK") {
    var userChoice = prompt("Invalid choice. Please pick ROCK, PAPER, SCISSORS, LIZARD or SPOCK.");
    var userChoice = userChoice.toUpperCase();
}

Apologies if it's mundane.

userChoice !== "ROCK" | "PAPER" | "SCISSORS" | "LIZARD" | "SPOCK"

should be

userChoice !== "ROCK" && userChoice !== "PAPER" && userChoice !== "SCISSORS" && userChoice !== "LIZARD" && userChoice !== "SPOCK"

Right now it is essentially checking if userChoice !== 0 as the whole right side of that is one expression and evaluates to 0.

In javascript, | by itself is a bitwise or. Since bitwise operations only make sense on integers, your strings get cast to integers, so you are basically doing 0 | 0, which will be 0.

You were probably thinking of || , which is a logical or, which I can see how you would think "if userChoice is not Rock or Paper or Scissors", but again, not how it works. You have to check if userChoice is not Rock, AND userChoice is not Scissors.

You would use || if you wanted to see if userChoice IS Rock, OR if userChoics is scissors, etc.

Per the comments, you could improve the code readability considerably by doing something like:

var choices = ["ROCK", "PAPER", "SCISSORS", "LIZARD", "SPOCK"];    
while(choices.indexOf(userChoice) == -1) {
     userChoice = prompt("Invalid choice. Please pick one of: " + 
                         choices.join(" ").toUpperCase());
}

Also, just to add in my personal favorite javascript trick, you can change

while(choices.indexOf(userChoice) == -1)

to

while(!~choices.indexOf(userChoice))

Or if you want to use something like not in, you can create an object like this:

var choice = {ROCK:{}, PAPER:{}, SCISSORS:{}, LIZARD:{}, SPOCK:{}};

And then modify the while statement as:

while (!(userChoice in choice))

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