javascript - 当我不知道需要比较多少东西时,使用 switch 语句最简单的方法是什么?
问题描述
所以我有一个终端,用户可以在其中输入命令。
我采用命令的第一句话并通过 switch 语句运行它来确定要做什么。
switch(phrases[0]) {
case "boot":
// Do something
break;
case "switch":
case "app":
case "change":
case "switchapp":
case "changeapp":
// Do something
break;
case "help":
// Do something
break;
case "wipe":
case "erase":
case "restart":
case "forget":
case "clear":
case "undo":
// Do something else here
break;
default:
throw new Error("Unknown command: " + phrases[0]);
}
请注意,对于每个命令,我都有一些替代方案,以使用户更有可能在第一次尝试时选择正确的命令。
但是 - 如果我将所有这些选项都放在一个数组中,而不是硬编码到 switch 函数中,我该如何访问它们?
我考虑过将 if/else 与 .some() 结合使用,但这似乎很笨拙:
if(bootCommands.some(function(name){return name == phrases[0]}))
// Do something
if(switchCommands.some(function(name){return name == phrases[0]})) {
// Do something
} else if(helpCommands.some(function(name){return name == phrases[0]})) {
// Do something
} else if(wipeCommands.some(function(name){return name == phrases[0]})) {
// Do something
} else {
throw new Error("Unknown command: " + phrases[0]);
}
肯定有更简单的方法吗?
解决方案
您仍然可以使用switch-case
表达式Array.includes()
switch(true) {
case bootCommands.includes(phrases[0]):
// Do something
break;
case wipeCommands.includes(phrases[0]):
// Do something
break;
default:
throw new Error("Unknown command: " + phrases[0]);
}
var bootCommands = ["boot"],
wipeCommands = ["wipe", "erase", "restart", "forget", "clear", "undo"],
command = "restart";
switch (true) {
case bootCommands.includes(command):
// Do something
console.log("Boot command: " + command);
break;
case wipeCommands.includes(command):
// Do something
console.log("Wipe command: " + command);
break;
default:
console.log("Unknown command: " + command);
}
推荐阅读
- javascript - 旋转平移的元素会移动元素
- excel-formula - 从表格中可用的数据中获得准确结果的公式
- c++ - 有没有办法从一个函数全局声明一个可变大小的向量?
- visual-studio - 使用 Qemu 在 Ubuntu 上的 Visual Studio Professional 远程调试 Arm64 程序
- sql - SQL Server 透视所有表列
- html - Flex div 没有占据其父级的全高
- apache - .htaccess Vanity/Nice URLs 导致 404 错误成为主页
- javascript - 如何通过仅在用户滚动到特定部分时调用它来减少谷歌地图 API 命中数
- excel - 如果工作表中的一个单元格不等于0,我该如何做减法
- laravel - 不能一下子在 laravel 宅基地上流浪