Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

jquery - Switch-Case for strings in Javascript not working as expected

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

Here event.keyCode has the value "65", and is the result of a keydown event of 'a' (using 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

keyCode is 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:

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 "input is equal to clauseSelector as defined by the === operator". input is 65 (integer) and clauseSelector is '65' (string) in my above example, which are not ===.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...