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
此规则不允许 if 语句作为 else 块中的唯一语句。
¥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();
}
何时不使用
¥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 中引入。