Index

no-plusplus

禁止使用一元运算符 ++--

❄️ Frozen

此规则目前已 冻结,不接受功能请求。

因为一元运算符 ++-- 会受到自动分号插入的影响,空白的差异可能会改变源代码的语义。

🌐 Because the unary ++ and -- operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code.

let i = 10;
let j = 20;

i ++
j
// i = 11, j = 20
let i = 10;
let j = 20;

i
++
j
// i = 10, j = 21

规则详情

🌐 Rule Details

此规则不允许使用一元运算符 ++--

🌐 This rule disallows the unary operators ++ and --.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

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

let foo = 0;
foo++;

let bar = 42;
bar--;

for (let i = 0; i < l; i++) {
    doSomething(i);
}

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

🌐 Examples of correct code for this rule:

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

let foo = 0;
foo += 1;

let bar = 42;
bar -= 1;

for (let i = 0; i < l; i += 1) {
    doSomething(i);
}

选项

🌐 Options

此规则有一个对象选项。

🌐 This rule has an object option.

  • "allowForLoopAfterthoughts": true 允许在 for 循环的后置条件(最终表达式)中使用一元运算符 ++--

allowForLoopAfterthoughts

使用 { "allowForLoopAfterthoughts": true } 选项时,此规则的正确代码示例:

🌐 Examples of correct code for this rule with the { "allowForLoopAfterthoughts": true } option:

在线运行
/*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/

for (let i = 0; i < l; i++) {
    doSomething(i);
}

for (let i = l; i >= 0; i--) {
    doSomething(i);
}

for (let i = 0, j = l; i < l; i++, j--) {
    doSomething(i, j);
}

使用 { "allowForLoopAfterthoughts": true } 选项时违反此规则的错误代码示例:

🌐 Examples of incorrect code for this rule with the { "allowForLoopAfterthoughts": true } option:

在线运行
/*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/

for (let i = 0; i < l; j = i++) {
    doSomething(i, j);
}

for (let i = l; i--;) {
    doSomething(i);
}

for (let i = 0; i < l;) i++;

版本

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

资源