首页 > 解决方案 > 如何将输入限制为数组中的单词之一?

问题描述

所以我正在制作一个小型炸弹拆除小游戏,在其中你从 6 种颜色的数组中获得 4 种随机颜色。您需要按照一些特定规则切割彩色电线。玩家需要输入例如“Blue”来切断蓝线,但我很难得到它,所以除了给定的 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}!`);

我也试过 (wire !== "Blue" || "Green" || "Yellow" || "Black" || "White") 但这也没有用。

完成这项工作的正确方法是什么?

标签: javascript

解决方案


您可以将允许的值放在一个数组中并使用该includes函数:

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

// ...

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

推荐阅读