no-plusplus

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

因为一元 ++-- 运算符会自动插入分号,所以空格的差异会改变源代码的语义。

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

var i = 10;
var j = 20;

i ++
j
// i = 11, j = 20
var i = 10;
var 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"*/

var foo = 0;
foo++;

var bar = 42;
bar--;

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

此规则的正确代码示例:

¥Examples of correct code for this rule:

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

var foo = 0;
foo += 1;

var bar = 42;
bar -= 1;

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

选项

¥Options

此规则有一个对象选项。

¥This rule has an object option.

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

    ¥"allowForLoopAfterthoughts": true allows unary operators ++ and -- in the afterthought (final expression) of a for loop.

allowForLoopAfterthoughts

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

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

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

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

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

for (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 (i = 0; i < l; j = i++) {
    doSomething(i, j);
}

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

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

版本

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

资源

ESLint 中文网
粤ICP备13048890号