1

我正在处理 switch 语句,并且一直在尝试使这里的代码正常工作,但它似乎没有输出正确的 console.log 案例字符串。

var user = prompt("What is your name?").toLowerCase();
switch(user){
    case "luka":
    console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
    break;

    case user.length > 10:
    console.log("That's a long name!");
    break;

    case user.length < 4:
    console.log("Not to be rude or impolite to you in any way, but your name is kinda       short :( Not that it isn't cool or something :D");
    break;

}

我试过像这样 (user).length < 4 那样在用户周围加上括号,但这不起作用,我的其他一些尝试也不起作用。有人知道如何正确实施吗?

4

3 回答 3

4

你不应该在 switch 语句中使用条件。

使用 if/else if

var user = prompt("What is your name?").toLowerCase();
if (user==="luka") {
    console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
} else if (user.length > 10) {
    console.log("That's a long name!");
} else if (user.length < 4) {
    console.log("Not to be rude or impolite to you in any way, but your name is kinda       short :( Not that it isn't cool or something :D");
} else {
    console.log("in else");
}
于 2013-03-07T14:59:25.020 回答
2

这不是 JavaScriptswitch语句的工作方式。“case”表达式中的值与switch表达式的值进行比较。

您在那里的声明相当于:

if (user === "luka") {
    console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
}
else if (user === (user.length > 10)) {
    console.log("That's a long name!");
}
else if (user === (user.length < 4)) {
    console.log("Not to be rude or impolite to you in any way, but your name is kinda       short :( Not that it isn't cool or something :D");    
}

因此,您将“用户”的值与与这些值进行比较的结果进行比较user.length。那些比较结果是布尔值,所以“使用”对他们来说永远不会===

于 2013-03-07T15:00:28.683 回答
2

switch在像您这样的情况下使用一种可能的解决方法:

var user = prompt("What is your name?").toLowerCase();
switch (true) {
    case (user === "luka"):
        console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
        break;

    case (user.length > 10):
        console.log("That's a long name!");
        break;

    case (user.length < 4):
        console.log("Not to be rude or impolite to you in any way, but your name is kinda       short :( Not that it isn't cool or something :D");
}

但是我会遵循@epascarello 的建议并使用if/else块。

于 2013-03-07T15:02:28.040 回答