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()
永遠不會執行。顯然,只有當 b
評估為 true
時才能執行 baz()
,但在這種情況下,會執行 bar()
,因為它在鏈中較早。
規則詳情
此規則不允許在同一 if-else-if
鏈中重複的條件。
此規則的錯誤程式碼範例
在遊樂場開啟
/*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();
}
此規則的正確程式碼範例
在遊樂場開啟
/*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();
}
此規則也可以偵測到一些條件不相同,但由於 ||
和 &&
運算子的邏輯,分支永遠無法執行的情況。
此規則的其他錯誤程式碼範例
在遊樂場開啟
/*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 中引入的。