Skip to content
← Back to rules

eslint/no-fallthrough 严格

An auto-fix is available for this rule.

它的作用

禁止 case 语句的自动穿透

此规则旨在消除无意中从一个 case 自动穿透到下一个 case 的情况。因此,它会标记所有未通过注释明确说明的自动穿透场景。

为什么这是个问题?

在 JavaScript 中,switch 语句是语言中最容易出错的结构之一,部分原因在于其允许从一个 case 自动穿透到下一个 case。例如:

js
switch (foo) {
  case 1:
    doSomething();

  case 2:
    doSomethingElse();
}

在此例中,如果 foo 的值为 1,则执行将依次进入两个 case,因为第一个 case 会自动穿透到第二个。你可以通过使用 break 来阻止这种行为,如下所示:

js
switch (foo) {
  case 1:
    doSomething();
    break;

  case 2:
    doSomethingElse();
}

当不希望发生自动穿透时,这种方式没有问题。但如果自动穿透是故意设计的,那么目前的语言中并没有一种方式可以明确表示这一点。最佳实践是始终通过符合 /falls?\s?through/i 正则表达式的注释来标明意图,但该注释不能是指令性内容:

js
switch (foo) {
  case 1:
    doSomething();
  // falls through

  case 2:
    doSomethingElse();
}

switch (foo) {
  case 1:
    doSomething();
  // fall through

  case 2:
    doSomethingElse();
}

switch (foo) {
  case 1:
    doSomething();
  // fallsthrough

  case 2:
    doSomethingElse();
}

switch (foo) {
  case 1: {
    doSomething();
    // falls through
  }

  case 2: {
    doSomethingElse();
  }
}

在此示例中,预期行为十分清晰。显然,第一个 case 是有意要穿透到第二个 case 的。

示例

此规则的 错误 代码示例:

js
switch (foo) {
  case 1:
    doSomething();

  case 2:
    doSomething();
}

此规则的 正确 代码示例:

js
switch (foo) {
  case 1:
    doSomething();
    break;

  case 2:
    doSomething();
}

function bar(foo) {
  switch (foo) {
    case 1:
      doSomething();
      return;

    case 2:
      doSomething();
  }
}

switch (foo) {
  case 1:
    doSomething();
    throw new Error("Boo!");

  case 2:
    doSomething();
}

switch (foo) {
  case 1:
  case 2:
    doSomething();
}

switch (foo) {
  case 1:
  case 2:
    doSomething();
}

switch (foo) {
  case 1:
    doSomething();
  // falls through

  case 2:
    doSomething();
}

switch (foo) {
  case 1: {
    doSomething();
    // falls through
  }

  case 2: {
    doSomethingElse();
  }
}

注意:在上述示例中,最后一个 case 语句不会触发警告,因为其后没有需要穿透的目标。

配置

此规则接受一个包含以下属性的配置对象:

allowEmptyCase

type: boolean

默认值: false

是否允许空的 case 子句自动穿透。

commentPattern

type: string

自定义正则表达式模式,用于匹配自动穿透注释。

reportUnusedFallthroughComment

type: boolean

默认值: false

是否报告未使用的自动穿透注释。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "no-fallthrough": "error"
  }
}
bash
oxlint --deny no-fallthrough

参考资料