default-case-last
强制 switch 语句中的默认子句在最后
switch
语句可以选择有一个 default
子句。
¥A switch
statement can optionally have a default
clause.
如果存在,它通常是最后一个子句,但不是必须的。也允许将 default
子句放在所有 case
子句之前,或介于两者之间。行为与最后一个子句基本相同。只有在 case
子句(包括 default
之后定义的)没有匹配的情况下,default
块仍然会被执行,但也可以 “跌倒” 从 default
子句到列表中的下一个子句。然而,这样的流程并不常见,它会让读者感到困惑。
¥If present, it’s usually the last clause, but it doesn’t need to be. It is also allowed to put the default
clause before all case
clauses, or anywhere between. The behavior is mostly the same as if it was the last clause. The default
block will be still executed only if there is no match in the case
clauses (including those defined after the default
), but there is also the ability to “fall through” from the default
clause to the following clause in the list. However, such flow is not common and it would be confusing to the readers.
即使没有 “跌倒” 逻辑,在 case
子句之前或之间看到 default
子句仍然是意料之外的。按照惯例,它应该是最后一个子句。
¥Even if there is no “fall through” logic, it’s still unexpected to see the default
clause before or between the case
clauses. By convention, it is expected to be the last clause.
如果 switch
语句应该有一个 default
子句,则将其定义为最后一个子句被认为是最佳实践。
¥If a switch
statement should have a default
clause, it’s considered a best practice to define it as the last clause.
规则详情
¥Rule Details
此规则强制 switch
语句中的 default
子句位于最后。
¥This rule enforces default
clauses in switch
statements to be last.
它仅适用于已经有 default
子句的 switch
语句。
¥It applies only to switch
statements that already have a default
clause.
此规则不强制 default
子句的存在。如果你还想强制在 switch
语句中存在 default
子句,请参见 default-case。
¥This rule does not enforce the existence of default
clauses. See default-case if you also want to enforce the existence of default
clauses in switch
statements.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint default-case-last: "error"*/
switch (foo) {
default:
bar();
break;
case "a":
baz();
break;
}
switch (foo) {
case 1:
bar();
break;
default:
baz();
break;
case 2:
quux();
break;
}
switch (foo) {
case "x":
bar();
break;
default:
case "y":
baz();
break;
}
switch (foo) {
default:
break;
case -1:
bar();
break;
}
switch (foo) {
default:
doSomethingIfNotZero();
case 0:
doSomethingAnyway();
}
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint default-case-last: "error"*/
switch (foo) {
case "a":
baz();
break;
default:
bar();
break;
}
switch (foo) {
case 1:
bar();
break;
case 2:
quux();
break;
default:
baz();
break;
}
switch (foo) {
case "x":
bar();
break;
case "y":
default:
baz();
break;
}
switch (foo) {
case -1:
bar();
break;
}
if (foo !== 0) {
doSomethingIfNotZero();
}
doSomethingAnyway();
相关规则
版本
此规则是在 ESLint v7.0.0-alpha.0 中引入。