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 注释测试模式

    ¥Set the commentPattern option to a regular expression string to change the default /^no default$/i comment test pattern

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 中引入。

资源

ESLint 中文网
粤ICP备13048890号