Javascript 中字符串的 Switch-Case 未按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2573145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:58:02  来源:igfitidea点击:

Switch-Case for strings in Javascript not working as expected

javascriptjquerystringswitch-statement

提问by Coltin

So I have this problem with strings and switch-case, and I'll try to keep it as simple as possible.

所以我对字符串和 switch-case 有这个问题,我会尽量保持简单。

Here event.keyCode has the value "65", and is the result of a keydown event of 'a' (using JQuery).

这里 event.keyCode 的值为“65”,是 'a' 的 keydown 事件的结果(使用 JQuery)。

if (event.keyCode == "65") {
   alert("hmmmm");
}

That works, but:

这有效,但是:

switch (event.keyCode) {
   case '65':
      alert("Yay!");
      break;
}

That doesn't. However this will work:

那没有。但是,这将起作用:

switch ('65') {
   case '65':
      alert("Yay!");
      break;
}

And if I do this:

如果我这样做:

var t = '65';
switch (t) {
   case '65':
      alert("Yay!");
      break;
}

It works. And then I tried this:

有用。然后我尝试了这个:

var t = event.keyCode;
switch (t) {
   case '65':
      alert("Yay!");
      break;
}

But it fails!

但它失败了!

So why does it match in the if-block at the beginning, but not for the switch-case?

那么为什么它在开头的 if 块中匹配,而在 switch-case 中不匹配?

回答by Matthew Flaschen

keyCodeis an integer, not a string. When you use ==, the conversion is done implicitly. However, the switch uses the equivalent of ===, which doesn't allow implicit conversions. You can test this easily with:

keyCode是一个整数,而不是一个字符串。当您使用 时==,转换是隐式完成的。但是,开关使用等效的===,它不允许隐式转换。您可以使用以下方法轻松测试:

switch (65) {
   case '65':
      alert("Yay!");
      break;
}

As expected, it does not alert.

正如预期的那样,它不会发出警报。

This is stated in ECMAScript, 5th edition section 12.11 (switch statement). The interpreter will enter a case statement if "inputis equal to clauseSelectoras defined by the === operator". inputis 65 (integer) and clauseSelector is '65' (string) in my above example, which are not ===.

这在ECMAScript,第 5 版第 12.11 节(switch 语句)中有说明。如果“input等于clauseSelector由 === 运算符定义”,解释器将输入 case 语句。 input在我上面的例子中是 65(整数),而 clauseSelector 是 '65'(字符串),它们不是===.