javascript - 如何将输入限制为数组中的单词之一?
问题描述
所以我正在制作一个小型炸弹拆除小游戏,在其中你从 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") 但这也没有用。
完成这项工作的正确方法是什么?
解决方案
您可以将允许的值放在一个数组中并使用该includes
函数:
const allowedValues = ["Blue", "Green", "Yellow", "Black", "White"];
// ...
if (!allowedValues.includes(userInput)) {
console.log('Invalid input');
}
推荐阅读
- selenium - 在 Selenium 中使用 Chromedriver
- matlab - @(filename)readAndPreprocessImage(filename) 中的错误
- typescript - 反应路线渲染属性类型挑战打字稿
- tensorflow - 如何访问序列类型的值?
- mysql - MySQL 1114 错误,表 /tmp/#sql 已满
- r - 处理已经在 r 中半汇总的数据
- api - 谷歌分析数据 API - 属性 ID
- qml - 如何跟踪 QML 粒子死亡
- python - Pandas 根据时间间隔删除重复的行
- android - Flutter generateJsonModelDebug 同时使用 ffi 包含的库