no-duplicate-case

不允许重复的案例标签

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

如果 switch 语句在 case 子句中有重复的测试表达式,则很可能程序员复制了 case 子句但忘记更改测试表达式。

¥If a switch statement has duplicate test expressions in case clauses, it is likely that a programmer copied a case clause but forgot to change the test expression.

规则详情

¥Rule Details

此规则不允许在 switch 语句的 case 子句中出现重复的测试表达式。

¥This rule disallows duplicate test expressions in case clauses of switch statements.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

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

var a = 1,
    one = 1;

switch (a) {
    case 1:
        break;
    case 2:
        break;
    case 1:         // duplicate test expression
        break;
    default:
        break;
}

switch (a) {
    case one:
        break;
    case 2:
        break;
    case one:         // duplicate test expression
        break;
    default:
        break;
}

switch (a) {
    case "1":
        break;
    case "2":
        break;
    case "1":         // duplicate test expression
        break;
    default:
        break;
}

此规则的正确代码示例:

¥Examples of correct code for this rule:

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

var a = 1,
    one = 1;

switch (a) {
    case 1:
        break;
    case 2:
        break;
    case 3:
        break;
    default:
        break;
}

switch (a) {
    case one:
        break;
    case 2:
        break;
    case 3:
        break;
    default:
        break;
}

switch (a) {
    case "1":
        break;
    case "2":
        break;
    case "3":
        break;
    default:
        break;
}

何时不使用

¥When Not To Use It

在极少数情况下,case 子句中的相同测试表达式产生不同的值,这必然意味着表达式导致并依赖于副作用,你将不得不禁用此规则。

¥In rare cases where identical test expressions in case clauses produce different values, which necessarily means that the expressions are causing and relying on side effects, you will have to disable this rule.

switch (a) {
    case i++:
        foo();
        break;
    case i++: // eslint-disable-line no-duplicate-case
        bar();
        break;
}

版本

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

资源

ESLint 中文网
粤ICP备13048890号