Eslint
规则 | Rules

no-else-return

在 else 之前不允许返回(无其他返回)

在命令行上的--fix选项可以自动修复一些被这条规则反映的问题。

如果一个if块包含一个return语句,else块就变得不必要了。它的内容可以放在块的外面。

function foo() { if (x) { return y; } else { return z; } }

规则细节

此规则旨在突出显示if包含 return 语句后的不必要代码块。因此,当它遇到else一连串的ifs 时,它会发出警告,所有这些都包含一个return声明。

选项

该规则有一个对象选项:

{ "no-else-return": ["error", { "allowElseIf": true }], // or "no-else-return": ["error", { "allowElseIf": false }] }

  • allowElseIf: true(默认)允许返回后的else if

  • allowElseIf: false禁止返回后的else if

allowElseIf: true

此规则的错误代码示例:

/*eslint no-else-return: "error"*/ function foo() { if (x) { return y; } else { return z; } } function foo() { if (x) { return y; } else if (z) { return w; } else { return t; } } function foo() { if (x) { return y; } else { var t = "foo"; } return t; } function foo() { if (error) { return 'It failed'; } else { if (loading) { return "It's still loading"; } } } // Two warnings for nested occurrences function foo() { if (x) { if (y) { return y; } else { return x; } } else { return z; } }

此规则的正确代码示例:

/*eslint no-else-return: "error"*/ function foo() { if (x) { return y; } return z; } function foo() { if (x) { return y; } else if (z) { var t = "foo"; } else { return w; } } function foo() { if (x) { if (z) { return y; } } else { return z; } } function foo() { if (error) { return 'It failed'; } else if (loading) { return "It's still loading"; } }

allowElseIf: false

此规则的错误代码示例:

/*eslint no-else-return: ["error", {allowElseIf: false}]*/ function foo() { if (error) { return 'It failed'; } else if (loading) { return "It's still loading"; } }

此规则的正确代码示例:

/*eslint no-else-return: ["error", {allowElseIf: false}]*/ function foo() { if (error) { return 'It failed'; } if (loading) { return "It's still loading"; } }

版本

该规则在 ESLint 0.0.9中引入。

资源