我理解下面的代码。
var day = 2;
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday!!");
break;
case 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
它打印出“星期二!!”。
但是,为什么下面的方法不起作用?我虽然它应该打印相同的答案,但它一直打印“另一天”!?
var day = 2;
switch (day) {
case day == 1:
document.write("Monday");
break;
case day == 2:
document.write("Tuesday!!");
break;
case day == 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
最佳答案
switch 语句中的 case 尝试直接与 switch 条件匹配。所以你的片段:
var day = 2;
switch (day) {
case day == 1:
document.write("Monday");
break;
case day == 2:
document.write("Tuesday!!");
break;
case day == 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
实际上相当于:
var day = 2;
switch (day) {
case false:
document.write("Monday");
break;
case true:
document.write("Tuesday!!");
break;
case false:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
并且由于 day
不等于 true
或 false
(因为它实际上是 2
>),开关会转为默认情况。
您可以看到案例使用 the docs 中的严格相等(强调我的):
A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing the associated statements.
关于javascript - JS : Why don't the switch statement cases `case 2` and `case day == 2` print out the same result?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47764486/