Skip to content

noDuplicateElseIf

诊断类别:lint/nursery/noDuplicateElseIf

¥Diagnostic Category: lint/nursery/noDuplicateElseIf

自从:v1.6.2

¥Since: v1.6.2

来源:

¥Sources:

禁止 if-else-if 链中的重复条件

¥Disallow duplicate conditions in if-else-if chains

当需要根据某些条件从几个可能的分支中仅执行一个分支(或最多一个分支)时,通常使用 if-else-if 链。

¥if-else-if chains are commonly used when there is a need to execute only one branch (or at most one branch) out of several possible branches, based on certain conditions.

同一链中的两个相同测试条件几乎总是代码中的错误。除非表达式中有副作用,否则重复项将评估为与链中较早的相同表达式相同的真值或假值,这意味着其分支永远无法执行。

¥Two identical test conditions in the same chain are almost always a mistake in the code. Unless there are side effects in the expressions, a duplicate will evaluate to the same true or false value as the identical expression earlier in the chain, meaning that its branch can never execute.

请注意,此规则不会将链中的条件与语句内的条件进行比较

¥Please note that this rule does not compare conditions from the chain with conditions inside statements

¥Examples

¥Invalid

if (a) {
foo();
} else if (b) {
bar();
} else if (b) {
baz();
}
code-block.js:5:12 lint/nursery/noDuplicateElseIf ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain.

3 │ } else if (b) {
4 │ bar();
> 5 │ } else if (b) {
^
6 │ baz();
7 │ }

¥Valid

if (a) {
foo();
} else if (b) {
bar();
} else if (c) {
baz();
}

¥Related links