jshint投出了一个"期待一个'休息'之前的陈述'案例'"

时间:2014-03-14 07:03:17

标签: javascript jshint

您好,我的框架使用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'. 有关如何避免它的任何想法?或者在这种情况下使用切换案例是不好的做法?

2 个答案:

答案 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;
  }
}