Index

default-case

switch 语句中要求 default 个案例

有些代码规范要求所有 switch 语句都必须有一个 default 情况,即使默认情况是空的,例如:

🌐 Some code conventions require that all switch statements have a default case, even if the default case is empty, such as:

switch (foo) {
    case 1:
        doSomething();
        break;

    case 2:
        doSomething();
        break;

    default:
    // do nothing
}

想法是最好总是明确说明默认行为应该是什么,这样开发者是否忘记了错误地包含默认行为就很清楚了。

🌐 The thinking is that it’s better to always explicitly state what the default behavior should be so that it’s clear whether or not the developer forgot to include the default behavior by mistake.

其他编码规范允许你跳过 default 情况,只要有评论说明省略是故意的,例如:

🌐 Other code conventions allow you to skip the default case so long as there is a comment indicating the omission is intentional, such as:

switch (foo) {
    case 1:
        doSomething();
        break;

    case 2:
        doSomething();
        break;

    // no default
}

再一次,这里的目的是表明开发者打算不存在默认行为。

🌐 Once again, the intent here is to show that the developer intended for there to be no default behavior.

规则详情

🌐 Rule Details

此规则旨在要求 switch 语句中的 default 情况。 如果没有 default 情况,你可以在最后的 case 后可选地包含一个 // no default。 注释可以使用任何所需的大小写,例如 // No Default

🌐 This rule aims to require default case in switch statements. You may optionally include a // no default after the last case if there is no default case. The comment may be in any desired case, such as // No Default.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint default-case: "error"*/

switch (a) {
    case 1:
        /* code */
        break;
}

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint default-case: "error"*/

switch (a) {
    case 1:
        /* code */
        break;

    default:
        /* code */
        break;
}

switch (a) {
    case 1:
        /* code */
        break;

    // no default
}

switch (a) {
    case 1:
        /* code */
        break;

    // No Default
}

选项

🌐 Options

此规则接受单个选项参数:

🌐 This rule accepts a single options argument:

  • commentPattern 选项设置为正则表达式字符串,以更改默认的 /^no default$/i 注释测试模式。

commentPattern

适用于 { "commentPattern": "^skip\\sdefault" } 选项的正确代码示例:

🌐 Examples of correct code for the { "commentPattern": "^skip\\sdefault" } option:

在线运行
/*eslint default-case: ["error", { "commentPattern": "^skip\\sdefault" }]*/

switch(a) {
    case 1:
        /* code */
        break;

    // skip default
}

switch(a) {
    case 1:
        /* code */
        break;

    // skip default case
}

何时不使用

🌐 When Not To Use It

如果你不想对 switch 语句强制执行 default 情况,你可以安全地禁用此规则。

🌐 If you don’t want to enforce a default case for switch statements, you can safely disable this rule.

版本

此规则是在 ESLint v0.6.0 中引入。

资源