no-lonely-if
不允许 if 语句作为 else 块中的唯一语句
如果 if 语句是 else 块中唯一的语句,通常使用 else if 形式会更清楚。
🌐 If an if statement is the only statement in the else block, it is often clearer to use an else if form.
if (foo) {
// ...
} else {
if (bar) {
// ...
}
}
应该改写为
🌐 should be rewritten as
if (foo) {
// ...
} else if (bar) {
// ...
}
规则详情
🌐 Rule Details
此规则不允许在 else 块中仅使用 if 语句。
🌐 This rule disallows if statements as the only statement in else blocks.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
在线运行
/*eslint no-lonely-if: "error"*/
if (condition) {
// ...
} else {
if (anotherCondition) {
// ...
}
}
if (condition) {
// ...
} else {
if (anotherCondition) {
// ...
} else {
// ...
}
}
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
在线运行
/*eslint no-lonely-if: "error"*/
if (condition) {
// ...
} else if (anotherCondition) {
// ...
}
if (condition) {
// ...
} else if (anotherCondition) {
// ...
} else {
// ...
}
if (condition) {
// ...
} else {
if (anotherCondition) {
// ...
}
doSomething();
}
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
何时不使用
🌐 When Not To Use It
如果代码在不使用 else if 形式的情况下更清晰,请禁用此规则。
🌐 Disable this rule if the code is clearer without requiring the else if form.
版本
此规则是在 ESLint v0.6.0 中引入。