当我想到一个奇怪的想法时,我正在构建代码,我可以在开关内实现/放置数组吗?

我的意思是,如何使codeHide案例起作用?这段代码不起作用。

当我要求设置命令并将hide()(即codeHide[0]放在codeHide数组上)时,我想switch接受codeHide的情况(我的if语句)并返回一个alert告诉我该特定数组元素的alertMessage

如果我将hide(background)(即codeHide[1]放在codeHide数组上)放在我想切换的codeHide情况下(我的if语句),然后返回一个alert告诉我alertMessage该特定数组元素(在is语句中)。

希望你能理解我。

这样做是行不通的,我认为是因为“ case codeHide:”。

到目前为止,这是我所做的:

var codeHide = ['hide()', 'hide(background)'];

$(".code").on("click", function () {
    var codePrompt = prompt("Set the code in the command line."),
    alertMessage = "",
    consoleMessage = "Used '" + codePrompt + "' command.";

switch (codePrompt) {
    case codeHide:
        if (codeHide[0]) {
            alertMessage = "Hiding elements...";
        } else {
            alertMessage = "Hiding Background...";
        }
        break;
    default:
        alertMessage = consoleMessage = "We are sorry but you entered a WRONG command, try again tho!\ntyped: " + codePrompt;
        break;
    }
    alert(alertMessage);
    console.log(consoleMessage);
});

最佳答案

switch通过使用身份运算符===将打开的值与每种可能的情况进行比较来进行操作。这意味着您可以将数组放入case内,并且可以按照指定的方式工作(但对于数组来说肯定不是很直观):

var x = [1];
var a = [1];

switch (x) {
    case [1]: alert("it's [1]!"); break;
    case a: alert("it's a!"); break;
    case x: alert("it's x!"); break;
}


这将警告“它是x!”,而您可能希望前面两种情况中的任何一种都足以触发。但这就是===的工作方式:

[1] === x   // false
a === x     // true
x === x     // true


因此,尽管您可以在技术上使用数组,但实际上在实际情况中这样做非常有用。

回到您的代码,因为您感兴趣的值是字符串,所以似乎将简单对象用作映射就可以了:

var commands = {
    "hide()": {
        alert: "Hiding elements...",
        console: "Blah blah"
    }.
    "hide(background)": {
        alert: "Hiding background...",
        console: "Blah blah"
    }.
};
var fallback = {
    alert: "Sorry, wrong command",
    console: "Sorry, wrong command"
};


然后可以让你写

var result = commands[input] || fallback;
alert(result.alert);
console.log(result.console);

09-25 17:18
查看更多