javascript - (如何)我可以在 switch 语句中使用 'or' 吗?

标签 javascript switch-statement

下面的代码对吗:

var user = prompt("Is programming awesome?").toUpperCase();
switch (user) {
    case 'HELL YEAH' || 'YES' || 'YEAH' || 'YEP' || 'YEA':
        console.log("That's what I'd expected!");
    break;
    case 'KINDA'||'CANT SAY':
        console.log("Oh, you'd like it when you'll be a pro!");
    break;
    case 'HELL NO'||'NO'||'NAH'||'NOPE'||'NA':
        console.log("You can't say that!");
    break;
    default:
        console.log("Wacha tryna say mate?");
    break;
}

我试过了。但它没有像我想要的那样工作。如果输入是 'hell no' 或 'hell yeah',它工作得很好,但所有后面的字符串都被忽略了!

最佳答案

我会使用包含您的答案的字典(对象)来解决这个问题,然后您可以使用 switch 语句中的函数进行检查。这比进行多个案例检查要简洁得多:

var user = prompt("Is programming awesome?").toUpperCase(); // 'HELL YEAH';

// 'dictionary' is just a JS object that has key/value pairs
// In this instance we have keys that map the case checks you were
// making and each has a corresponding array for its value, filled with
// the OR checks you wanted to make.
// We pass 'dict' in as the second parameter when we call checkAnswer
var dict = {
    yes: ['HELL YEAH', 'YES', 'YEAH', 'YEP', 'YEA'],
    maybe: ['KINDA', 'CANT SAY'],
    no: ['HELL NO', 'NO', 'NAH', 'NOPE', 'NA']
};

// checkAnswer returns 'yes' for the user prompt 'HELL YEAH'
// It loops over the 'dict' object and if it finds an instance of
// your user input in one of the arrays it returns the key
// in this instance 'yes' for 'HELL YEAH' (indexOf returns 0)
// otherwise it returns false (for your 'default' case)
function checkAnswer(user, dict) {
    for (var p in dict) {
        if (dict[p].indexOf(user) > -1) return p;
    }
    return false;
}

// All we do is use checkAnswer to return the key where
// the user input is found in one of the dictionary arrays.
// That will always be a single string which is what switch expects
switch (checkAnswer(user, dict)) {
    case 'yes':
        console.log("That's what I'd expected!");
        break;
    case 'maybe':
        console.log("Oh, you'd like it when you'll be a pro!");
        break;
    case 'no':
        console.log("You can't say that!");
        break;
    default:
        console.log("Wacha tryna say mate?");
        break;
}

DEMO

关于javascript - (如何)我可以在 switch 语句中使用 'or' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30640278/

相关文章:

javascript - 计算百分比余数

C++ 用户输入关闭程序调试

c# - 处理枚举时没有默认的switch语句

javascript - 如何在node.js中获取实时生成的childProcess.stdout

javascript - 简单的 javascript 验证会阻止用户在输入无效日期格式时提交表单?

javascript - JQuery:如何选择表格行,但不选择单元格内表格的行

javascript - 对 React Components 的流类型感到困惑

c - 我在 C 中的开关(在 while 循环内)在正常运行之前直接进入默认状态

c - 嵌套开关: why does the second switch command not accept an input?

ios - 在 Obj-C 中使用 Switch 语句