no-else-return
禁止 if
语句中的 return
语句之后的 else
块
此规则报告的一些问题可通过 --fix
命令行选项自动修复
如果 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
之后的不必要的代码块。因此,当遇到 else
跟在一系列 if
后面(所有这些都包含 return
语句)时,它会触发警告。
¥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 if
s, all of them containing a return
statement.
选项
¥Options
此规则有一个对象选项:
¥This rule has an object option:
-
allowElseIf: true
(默认)在返回后允许else if
块¥
allowElseIf: true
(default) allowselse if
blocks after a return -
返回后
allowElseIf: false
不允许else if
块¥
allowElseIf: false
disallowselse if
blocks after a return
allowElseIf:true
此规则的错误代码示例:
¥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 if (z) {
return w;
} else {
return t;
}
}
function foo3() {
if (x) {
return y;
} else {
var t = "foo";
}
return t;
}
function foo4() {
if (error) {
return 'It failed';
} else {
if (loading) {
return "It's still loading";
}
}
}
// Two warnings for nested occurrences
function foo5() {
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;
} else if (z) {
var t = "foo";
} else {
return w;
}
}
function foo3() {
if (x) {
if (z) {
return y;
}
} else {
return z;
}
}
function foo4() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}
allowElseIf:false
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
function foo() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*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 中引入。