[removed] How can I simplify an if-statement with multiple OR conditions?

前端 未结 6 956
半阙折子戏
半阙折子戏 2021-01-16 17:22

Sorry if I\'ve made mistakes writing this post. I\'m new here and I don\'t know how this works, hope I learn quick. I am also new at JavaScript.

So the question is:

6条回答
  •  一整个雨季
    2021-01-16 17:56

    The "normal" way works the way you probably expect.

    However, that if statement is redundant, anyway. You can just skip it:

    if (codePrompt === codeSwitch) {
        alert("Switching background...");
        console.log("Used '" + codeSwitch + "' command.");
    } else if (codePrompt === codeBlur) {
        alert("Blurring elements...");
        console.log("Used '" + codeBlur + "' command.");
    } else if (codePrompt === codeSwitchBG) {
        alert("Switching background...");
        console.log("Used '" + codeSwitchBG + "' command.");
    } else if (codePrompt === codeShowInfo) {
        alert("Showing info...");
        console.log("Used '" + codeShowInfo + "' command.");
    } else {
        alert("Wrong command, try again.");
        console.log("Wrong command, try again.");
    }
    

    This is a good use case for a switch, and I would refactor it this way:

    var alertMessage = "",
        consoleMessage = "Used '" + codePrompt + "' command.";
    switch (codePrompt) {
        case codeSwitch:
            alertMessage = "Switching background...";
            break;
        case codeBlur:
            alertMessage = "Blurring elements...";
            break;
        case codeSwitchBG:
            alertMessage = "Switching background...";
            break;
        case codeShowInfo:
            alertMessage = "Showing info...";
            break;
        default:
            alertMessage = consoleMessage = "Wrong command, try again.";
            break;
    }
    alert(alertMessage);
    console.log(consoleMessage);
    

提交回复
热议问题