no-else-return
禁止 if 语句中的 return 语句之后的 else 块
如果一个 if 块包含一个 return 语句,那么 else 块就变得不必要。它的内容可以放在块的外面。
🌐 If an if block contains a return statement, the else block becomes unnecessary. Its contents can be placed outside of the block.
function foo() {
if (x) {
return y;
} else {
return z;
}
}
规则详情
🌐 Rule Details
此规则旨在高亮在包含 return 语句的 if 之后的不必要的代码块。因此,当它遇到紧跟一系列包含 return 语句的 if 的 else 时,它会发出警告。
🌐 This rule is aimed at highlighting an unnecessary block of code following an if containing a return statement. As such, it will warn when it encounters an else following a chain of ifs, all of them containing a return statement.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-else-return: "error"*/
function foo1() {
if (x) {
return y;
} else {
return z;
}
}
function foo2() {
if (x) {
return y;
} else {
const t = "foo";
}
}
function foo3() {
if (error) {
return 'It failed';
} else {
if (loading) {
return "It's still loading";
}
}
}
// Two warnings for nested occurrences
function foo4() {
if (x) {
if (y) {
return y;
} else {
return x;
}
} else {
return z;
}
}
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint no-else-return: "error"*/
function foo1() {
if (x) {
return y;
}
return z;
}
function foo2() {
if (x) {
return y;
}
const t = "foo";
}
function foo3() {
if (error) {
return 'It failed';
}
if (loading) {
return "It's still loading";
}
}
function foo4() {
if (x) {
if (y) {
return y;
}
return x;
}
return z;
}
function foo5() {
if (x) {
const t = "foo";
} else {
return y
}
}
选项
🌐 Options
allowElseIf
此规则有一个对象选项:
🌐 This rule has an object option:
allowElseIf: true(default)- 如果为真,允许在return之后使用else if块
默认 {"allowElseIf": true} 选项的正确代码示例:
🌐 Examples of correct code for the default {"allowElseIf": true} option:
/*eslint no-else-return: ["error", {allowElseIf: true}]*/
function foo() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}
// Using multiple `if` statements instead of `else if` is also allowed
function foo2() {
if (error) {
return 'It failed';
}
if (loading) {
return "It's still loading";
}
}
针对 {"allowElseIf": false} 选项的错误代码示例:
🌐 Examples of incorrect code for the {"allowElseIf": false} option:
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
function foo() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}
适用于 {"allowElseIf": false} 选项的正确代码示例:
🌐 Examples of correct code for the {"allowElseIf": false} option:
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
function foo() {
if (error) {
return 'It failed';
}
if (loading) {
return "It's still loading";
}
}
版本
此规则是在 ESLint v0.0.9 中引入。