I want the user to input his answer in a rock-paper-scissors game in the following line of code.
userChoice = prompt("Do you choose rock, paper or scissors?");
However, in case the user writes something other than exactly "rock", "paper" or "scissors", he is supposed to choose again, which I tried to do with this piece of code:
while (userChoice !== "rock" || "paper" || "scissors") {
userChoice = prompt("Invalid choice. Please change your answer.");
};
The problem I have is that the program keeps recognizing the given input as invalid, even if it is "rock", "paper" or "scissors".
While typing this, I managed to find a solution on my own.
while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors") {
userChoice = prompt("Invalid choice. Please change your answer.");
};
That way does make sense and the first condition probably didn't work because even if you type a correct answer (e.g. "paper"), it still doesn't equal the other two answers (in this case "rock" and "scissors"), which is why the program kept saying the answer has been invalid, right? Or is it a syntax error? Now (with the working condition), the choice of the user has to be neither "rock" nor "paper" nor "scissors" and thus it works properly.
Also, is there possibly an easier and shorter way of writing that condition?
Note: I hope it's fine that parts of the solution are already included as they could help other coders.
Two examples
One with an array and Array.prototype.indexOf()
:
var userChoice;
while (!~['rock', 'paper', 'scissors'].indexOf(userChoice)) {
userChoice = prompt("Invalid choice. Please change your answer.");
};
And another with an object and the in
operator:
The in operator returns
true
if the specified property is in the specified object.
var userChoice;
while (!(userChoice in {rock: 1, paper: 1, scissors: 1})) {
userChoice = prompt("Invalid choice. Please change your answer.");
};