admin管理员组文章数量:1326099
elmid = "R125";
switch(true){
case elmid.match(/R125/):
idType = "reply";
break;
}
alert(idType); // Returns undefined
-------------------BUT----------------------
elmid = "R125";
if (elmid.match(/R125/)){idType = "reply";}
alert(idType); // Returns "reply"
Using the swtich returns undefined but using an if returns the expected value, what is causeing the switch to fail ? Why is this the case? what am i doing wrong here? can any one explain why I get different results =).
NOTE: No advices to use an if statement in this case I know that, my question concise for asking there hence there is not only 1 case in the switch statement.
elmid = "R125";
switch(true){
case elmid.match(/R125/):
idType = "reply";
break;
}
alert(idType); // Returns undefined
-------------------BUT----------------------
elmid = "R125";
if (elmid.match(/R125/)){idType = "reply";}
alert(idType); // Returns "reply"
Using the swtich returns undefined but using an if returns the expected value, what is causeing the switch to fail ? Why is this the case? what am i doing wrong here? can any one explain why I get different results =).
NOTE: No advices to use an if statement in this case I know that, my question concise for asking there hence there is not only 1 case in the switch statement.
Share Improve this question asked Aug 16, 2010 at 6:40 Abdullah KhanAbdullah Khan 2,4253 gold badges23 silver badges34 bronze badges3 Answers
Reset to default 11elmid.match(/R125/)
This returns the actual regex matches, not true or false.
When you're writing an if statement and using ==
, some basic type conversion can be performed so that it works as expected. Switch statements use the identity parison (===
), and so this won't work.
If you want to do it this way, use regex.test() (which returns a boolean) instead.
case /R125/.test(elmid):
.match
returns the matches that matched the RegEx, not just true
or false
.
In a switch
statement, the test values are pared using ===
, not ==
.
So the resulting expression ["R125"] === true
is not true and the case
never executed.
The match function returns an array or null, so it will never return "true". But you are passing true into the switch statement, so all you are able to check against is "true". See the match() defintion
Match Definition
But if you are using an if statement (with the == operator instead the === operator), also the found array will be valid as true in the if statement.
本文标签: Problem with javascript switch statementStack Overflow
版权声明:本文标题:Problem with javascript switch statement - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742193764a2430697.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论