gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:52:52 28 4
gpt4 key购买 nike

我理解下面的代码。

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/

28 4 0
文章推荐: javascript - Dynamics crm 获取关联 View 上子网格的名称
文章推荐: sql-server - SSRS 报告表添加列表达式记录 x of y?
文章推荐: sql - 如何获取格式为 MM/DD/YYYY 的最新日期顺序
文章推荐: javascript - 为什么我在此