规范指南

no-plusplus

2021-02-13  本文已影响0人  越前君

假如我们使用 ESLint 来检查代码质量,且启用了其中一条规则 no-plusplus(禁止使用一元操作符 ++--),下面代码就会提示错误。

// Unary operator '++' used. eslint (no-plusplus)
for (let i = 0; i < 10; i++) {
  // ...
}

由于一元 ++-- 运算符都受自动插入分号机制(Automatic Semicolon Insertion,简称 ASI)的影响,因此空格的差异可能会改变源代码的语义。

var i = 10;
var j = 20;

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

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

此规则的错误代码示例:

/*eslint no-plusplus: "error"*/

var foo = 0;
foo++;

var bar = 42;
bar--;

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

此规则的正确代码示例:

/*eslint no-plusplus: "error"*/

var foo = 0;
foo += 1;

var bar = 42;
bar -= 1;

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

选项

该规则还有一个选项 { "allowForLoopAfterthoughts": true },它允许在 for 循环中使用一元运算符 ++--

此规则的正确代码示例包含以下 { "allowForLoopAfterthoughts": true } 选项:

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

for (let i = 0; i < 10; i++) {
  // ...
}

for (let i = 10; i > 0; i--) {
  // ...
}

此规则的错误代码示例包含以下 { "allowForLoopAfterthoughts": true } 选项:

/*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/
let i, j, l;

for (i = 0, j = l; i < l; i++, j--) {
  // ...
}

for (let i = 0; i < 10; j = i++) {
  // ...
}

for (i = l; i--;) {
  // ...
}

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

参考

上一篇 下一篇

猜你喜欢

热点阅读