我正在处理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;
}
我已经尝试过像这样(用户)在用户周围放置paranthesis .length&lt; 4,但这不起作用,也不是我的其他一些尝试。有人知道如何正确实现这个吗?
答案 0 :(得分: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");
}
答案 1 :(得分:2)
这不是JavaScript switch
语句的工作方式。 “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
与这些值进行比较的结果进行比较。那些比较结果是布尔值,因此“使用”将永远成为===
。
答案 2 :(得分: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's建议并使用if/else
块。