eslint/no-fallthrough 吹毛求疵
作用
禁止 case
陳述式中的 fallthrough 行為
此規則旨在消除無意中從一個 case 掉落到另一個 case 的情況。因此,它會標記任何未用註解標記的 fallthrough 情境。
為何這不好?
JavaScript 中的 switch 陳述式是該語言中較容易出錯的結構之一,部分原因是它具有從一個 case 「掉落」到下一個 case 的能力。例如
js
switch (foo) {
case 1:
doSomething();
case 2:
doSomethingElse();
}
在此範例中,如果 foo
為 1
,則執行會流經這兩個 case,因為第一個 case 會掉落到第二個 case。您可以使用 break
來避免這種情況,如以下範例所示
js
switch (foo) {
case 1:
doSomething();
break;
case 2:
doSomethingElse();
}
當您不想要 fallthrough 時,這運作良好,但是如果 fallthrough 是故意的,則沒有辦法在語言中指示這一點。最佳實務是使用符合 `/falls?\s?through/i`` 正規表達式的註解來指示 fallthrough 是故意的,但不是指令
js
switch (foo) {
case 1:
doSomething();
// falls through
case 2:
doSomethingElse();
}
switch (foo) {
case 1:
doSomething();
// fall through
case 2:
doSomethingElse();
}
switch (foo) {
case 1:
doSomething();
// fallsthrough
case 2:
doSomethingElse();
}
switch (foo) {
case 1: {
doSomething();
// falls through
}
case 2: {
doSomethingElse();
}
}
在此範例中,對於預期的行為沒有任何混淆。很明顯,第一個 case 是要掉落到第二個 case。
範例
此規則的不正確程式碼範例
js
/*oxlint no-fallthrough: "error"*/
switch (foo) {
case 1:
doSomething();
case 2:
doSomething();
}
此規則的正確程式碼範例
js
/*oxlint no-fallthrough: "error"*/
switch (foo) {
case 1:
doSomething();
break;
case 2:
doSomething();
}
function bar(foo) {
switch (foo) {
case 1:
doSomething();
return;
case 2:
doSomething();
}
}
switch (foo) {
case 1:
doSomething();
throw new Error("Boo!");
case 2:
doSomething();
}
switch (foo) {
case 1:
case 2:
doSomething();
}
switch (foo) {
case 1:
case 2:
doSomething();
}
switch (foo) {
case 1:
doSomething();
// falls through
case 2:
doSomething();
}
switch (foo) {
case 1: {
doSomething();
// falls through
}
case 2: {
doSomethingElse();
}
}
請注意,這些範例中的最後一個 case 陳述式不會產生警告,因為沒有任何東西可以掉落到其中。