首页 > 解决方案 > 当我不知道需要比较多少东西时,使用 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]);
}

肯定有更简单的方法吗?

标签: javascriptswitch-statement

解决方案


您仍然可以使用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);
}


推荐阅读