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

Per*_*ner 4 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;
}
Run Code Online (Sandbox Code Playgroud)

我尝试过这个.但它没有按照我的意愿行事.如果输入是'地狱没有'或'地狱是的',它运作良好,但所有后来的字符串都被忽略了!

And*_*ndy 6

我会使用包含您的答案的字典(对象)来处理此问题,然后您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

DEMO