Chan Kim
Chan Kim

Reputation: 177

How can I restrict the input to be one of the words in the array?

So I'm making a small bomb defusing minigame where you are given 4 random colors from an array of 6 colors. You need to cut the colored wires following some specific rules. The player needs to input for example "Blue" to cut the blue wire, but I'm having a hard time trying to get it so they can't type anything other than the 4 colors they are given.

const asdf = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});
let colorWithoutTypedColor
asdf.question('What will you cut?' , wire => { //First part where you are given 4 colors
        if (wire !== fourRandomColors[0 || 1 || 2 || 3]){
            console.log("You didn't pick a color!")
            return;
        }
        console.log(`You cut ${wire}!`);

I also tried (wire !== "Blue" || "Green" || "Yellow" || "Black" || "White") but that didn't work either.

What is the correct way to get this done?

Upvotes: 0

Views: 35

Answers (1)

Andreas Dolk
Andreas Dolk

Reputation: 114817

You can put the allowed values in an array and use the includes function:

const allowedValues = ["Blue", "Green", "Yellow", "Black", "White"];

// ...

if (!allowedValues.includes(userInput)) {
   console.log('Invalid input');
}

Upvotes: 1

Related Questions