Javascript 如何将输入限制为数组中的一个字?

Javascript 如何将输入限制为数组中的一个字?,javascript,Javascript,所以我正在制作一个小型的炸弹拆除小游戏,在这个游戏中,你可以从6种颜色的数组中随机获得4种颜色。您需要按照一些特定规则切割彩色导线。玩家需要输入例如蓝色来切割蓝色的线,但是我很难得到它,所以他们除了输入4种颜色之外不能输入任何东西 const asdf = require('readline').createInterface({ input: process.stdin, output: process.stdout }); let colorWithoutTypedColor

所以我正在制作一个小型的炸弹拆除小游戏,在这个游戏中,你可以从6种颜色的数组中随机获得4种颜色。您需要按照一些特定规则切割彩色导线。玩家需要输入例如蓝色来切割蓝色的线,但是我很难得到它,所以他们除了输入4种颜色之外不能输入任何东西

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}!`);
我还试过电线!==蓝色| | | |绿色| |黄色| |黑色| | | |白色,但这也不起作用


完成此操作的正确方法是什么?

您可以将允许的值放入数组中,并使用includes函数:

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

// ...

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

用法:如果['blue','green','yellow','black','yellow].indexOfwire==-1如果找不到任何颜色,它将返回-1,但如果找到其中一种颜色,它将返回一个非-1的值。indexOf的替代方法是:if![…]包括电线{。。。