javascript jshint 抛出“在‘case’之前需要‘break’语句”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22398251/
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
jshint throws a"Expected a 'break' statement before 'case'"
提问by sakthisundar
Hi I am having a trouble when my framework is using jshint to validate my javascript
code. I have used switch-case without a break statement intentionally, but this portion of code is captured as an error when jshint
checks. My code is something like below.
嗨,当我的框架使用 jshint 来验证我的javascript
代码时,我遇到了麻烦。我故意使用了没有 break 语句的 switch-case,但是这部分代码在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'.
Any thoughts on how to avoid it ? or is it a bad practice to use switch cases in this scenario at all ?
Error from 'jshint' is like Line 203 character 41: Expected a 'break' statement before 'case'.
关于如何避免它的任何想法?或者在这种情况下使用 switch case 是一种不好的做法吗?
回答by Gerald Schneider
Copy & paste from the documentation:
从文档中复制和粘贴:
Switch statements
By default JSHint warns when you omit break or return statements within switch statements:
[...]
If you really know what you're doing you can tell JSHint that you intended the case block to fall through by adding a
/* falls through */
comment
开关语句
默认情况下,当您在 switch 语句中省略 break 或 return 语句时,JSHint 会发出警告:
[...]
如果你真的知道你在做什么,你可以通过添加
/* falls through */
评论告诉 JSHint 你打算通过 case 块
So in your case:
所以在你的情况下:
switch (<no>) {
case 1:
// does something
/* falls through */
case 2:
//does something more
/* falls through */
default:
// does something even more
}
回答by Jo?o Pimentel Ferreira
Exactly, break
s may be totally superfluous, like in this example
确切地说,break
s 可能完全是多余的,就像在这个例子中一样
function mapX(x){
switch (x){
case 1:
return A;
case 2:
return B;
default:
return C;
}
}
In this case, if you would have had a break
after return
, JS Standardwould throw a warning, namely Unreachable code
.
在这种情况下,如果你有一个break
after return
,JS Standard会抛出一个警告,即Unreachable code
.
Trying to conciliate jshint and JS Standard is tricky, but as stated, the solution would be
试图调和 jshint 和 JS 标准是棘手的,但如上所述,解决方案是
function mapX(x){
switch (x){
case 1:
return A;
/* falls through */
case 2:
return B;
/* falls through */
default:
return C;
}
}