no-dupe-else-if
禁止在 if-else-if 链中出现重复条件
✅ 推荐
在配置文件中使用 @eslint/js 的 recommended 配置启用此规则
当需要根据特定条件从几个可能的分支中只执行一个分支(或最多一个分支)时,通常使用 if-else-if 链。
if (a) {
foo();
} else if (b) {
bar();
} else if (c) {
baz();
}
在同一链中出现两个相同的测试条件几乎总是代码中的错误。除非表达式中存在副作用,否则重复条件将评估为与链中较早的相同表达式相同的 true 或 false 值,这意味着它的分支永远不会执行。
if (a) {
foo();
} else if (b) {
bar();
} else if (b) {
baz();
}
在上面的例子中,baz() 永远不会执行。 显然,baz() 只有在 b 评估为 true 时才能执行,但在这种情况下,bar() 会被执行,因为它在链中更早。
规则详情
此规则禁止在同一 if-else-if 链中出现重复条件。
此规则的 错误 代码示例
在 Playground 中打开
/*eslint no-dupe-else-if: "error"*/
if (isSomething(x)) {
foo();
} else if () {
bar();
}
if (a) {
foo();
} else if (b) {
bar();
} else if (c && d) {
baz();
} else if () {
quux();
} else {
quuux();
}
if (n === 1) {
foo();
} else if (n === 2) {
bar();
} else if (n === 3) {
baz();
} else if () {
quux();
} else if (n === 5) {
quuux();
}
此规则的 正确 代码示例
在 Playground 中打开
/*eslint no-dupe-else-if: "error"*/
if (isSomething(x)) {
foo();
} else if (isSomethingElse(x)) {
bar();
}
if (a) {
foo();
} else if (b) {
bar();
} else if (c && d) {
baz();
} else if (c && e) {
quux();
} else {
quuux();
}
if (n === 1) {
foo();
} else if (n === 2) {
bar();
} else if (n === 3) {
baz();
} else if (n === 4) {
quux();
} else if (n === 5) {
quuux();
}
此规则还可以检测到某些条件不相同的情况,但由于 || 和 && 运算符的逻辑,该分支永远不会执行。
此规则的更多 错误 代码示例
在 Playground 中打开
/*eslint no-dupe-else-if: "error"*/
if (a || b) {
foo();
} else if () {
bar();
}
if (a) {
foo();
} else if (b) {
bar();
} else if () {
baz();
}
if (a) {
foo();
} else if () {
bar();
}
if (a && b) {
foo();
} else if () {
bar();
}
if (a || b) {
foo();
} else if () {
bar();
}
if (a) {
foo();
} else if (b && c) {
bar();
} else if () {
baz();
}
请注意,此规则不会将链中的条件与语句内的条件进行比较,并且不会在以下情况下发出警告
if (a) {
if (a) {
foo();
}
}
if (a) {
foo();
} else {
if (a) {
bar();
}
}
何时不使用
在极少数情况下,您确实需要在同一链中使用相同的测试条件,这必然意味着链中的表达式正在导致和依赖副作用,您将不得不关闭此规则。
相关规则
版本
此规则在 ESLint v6.7.0 中引入。