您好,我的框架使用jshint验证我的javascript
代码时遇到了麻烦。我故意使用了switch-case而没有break语句,但是当jshint
检查时,这部分代码被捕获为错误。我的代码如下所示。
switch (<no>){
case 1:
// does something
case 2:
//does something more
default:
// does something even more
}
Error from 'jshint' is like Line 203 character 41: Expected a 'break' statement before 'case'.
有关如何避免它的任何想法?或者在这种情况下使用切换案例是不好的做法?
答案 0 :(得分:114)
复制&amp;粘贴from the documentation:
切换声明
默认情况下,JSHint会在switch语句中省略break或return语句时发出警告:
[...]
如果你真的知道你在做什么,你可以告诉JSHint你 通过添加
来打算通过案例块/* falls through */
评论
所以在你的情况下:
switch (<no>) {
case 1:
// does something
/* falls through */
case 2:
//does something more
/* falls through */
default:
// does something even more
}
答案 1 :(得分:0)
确实,break
可能完全是多余的,如本例所示
function mapX(x){
switch (x){
case 1:
return A;
case 2:
return B;
default:
return C;
}
}
在这种情况下,如果在break
之后加上return
,则JS Standard会发出警告,即Unreachable code
。
试图调和jshint和JS Standard是很棘手的,但是如上所述,解决方案是
function mapX(x){
switch (x){
case 1:
return A;
/* falls through */
case 2:
return B;
/* falls through */
default:
return C;
}
}