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

前端 未结 6 962
半阙折子戏
半阙折子戏 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:52

    You could also refactor as follows to cut out the if/switch:

    var commands = {
        'switch()': 'Switching background',
        'switch(background)': 'Switching background',
        'blur()': 'Blurring elements',
        'showInfo()': 'Showing info'
    };
    
    $(".code").on("click", function () {
        var codePrompt = prompt("Set the code in the command line.");
        if (commands.hasOwnProperty(codePrompt)) {
            alert(commands[codePrompt] + '...');
            console.log("Used '" + codePrompt + "' command.");
        } else {
            alert("Wrong command, try again.");
            console.log("Wrong command, try again.");
        }
    });
    

提交回复
热议问题