javascript - JS : Why don't the switch statement cases `case 2` and `case day == 2` print out the same result?

标签 javascript switch-statement

我理解下面的代码。

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 不等于 truefalse (因为它实际上是 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/

相关文章:

javascript - undefined variable 作为函数参数 javascript

c# - LINQ:如何向 LINQ 查询添加多个变量?

javascript - Angularjs: Uncaught ReferenceError $rootScope 未定义

javascript - 将 javascript 数组传递到另一个页面

javascript - JavaScript 对象中包含数组的问题

java - 无法正确构建具有正确运行条件的 do while 循环

c# - 具有动态参数的整数类型预期开关的值

c - 关于 for 和 switch 的正确/错误

java - 尽管类在 switch block 中实例化,但它只能调用接口(interface)方法

javascript - AngularJs DatePicker 不显示 View