看起来
javascript开关案例不喜欢正则表达式作为一个案例,因为它与静态值一起使用但我无法在case语句中使用正则表达式获得预期的答案.
您是否会确认js解释器的限制并提出解决方法(我的意思是不是if-then块套件)?
谢谢
示例(未给出预期答案,例如’case3′):
<script type="text/javascript"> var testme = "pwd_foo"; var response = false; var reg = /^pwd.+/; switch (testme) { case 'pwd': response = 'case1'; break; case reg.test: response = 'case2'; break; case /^pwd.+/: response = 'case3'; break; default: response = 'do sthg else'; } alert('reg test: ' + reg.test(testme)+'\nresponse:' + response); </script>
解决方法
你的测试并没有真正适合转换.如果必须,你可以这样做,不推荐:
var testme = "pwd_foo",response; var reg = /^pwd.+/; switch (true) { case testme=='pwd': response = 'case1'; break; case reg.test(testme): response = 'case2'; break; default: response = 'do sthg else'; } alert('reg test: ' + reg.test(testme)+'\nresponse:' + response);