【问题标题】:eslint error Unary operator '++' used no-pluspluseslint错误一元运算符'++'使用了no-plusplus
【发布时间】:2021-04-14 03:47:23
【问题描述】:

如果我将i++ 用于loop,我的for 循环会出错

var foo = 0;
    foo++;
    
    var bar = 42;
    bar--;
    
    for (i = 0; i < 1; i++) {
        return;
    }

【问题讨论】:

  • i 是在哪里定义的?为什么循环里面有return语句? -- 啊,例子来自eslint.org/docs/rules/no-plusplus
  • return 语句只能出现在函数体中。
  • @MehpalPatidar 请考虑勾选以下答案之一
  • 请注意,这本身不是编程错误。只是您的默认配置和/或您使用的编码风格不允许前缀/后缀递增/递减运算符。无论如何,正如一些答案中指出的那样,您可以将 i++ 替换为 i += 1 以消除违规行为。

标签: javascript node.js reactjs eslint


【解决方案1】:

一种选择是将i++ 替换为i+=1

您还可以关闭特定的 eslint 规则(针对特定行、文件或全局配置)。请注意这可能不推荐,尤其是在文件或行级别。

您要查找的规则名称是no-plusplus

全局禁用

在您的 eslint 配置文件中添加以下内容:

'no-plusplus': 'off' **OR** 'no-plusplus': 0

还有一个选项可以仅对 for 循环禁用它:

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

更多信息您可以查看eslint no-plusplus docs

在文件级别禁用它

在文件顶部添加以下内容:

/* eslint-disable no-plusplus */

对给定的行禁用它

就在for循环之前,添加以下内容:

/* eslint-disable-next-line no-plusplus */

【讨论】:

    【解决方案2】:

    我已经解决了这个问题

    如果我们在代码中使用 i++,eslint 会报错。为了避免这种类型的错误,我们必须使用

    var foo = 0;
    foo += 1;
    
    var bar = 42;
    bar -= 1;
    
    for (i = 0; i < l; i += 1) {
        return;
    }
    

    谢谢

    【讨论】:

      【解决方案3】:

      如您所见,这是一个 linting 错误。要么这样写代码,

      foo += 1;

      i += 1
      

      或者关闭那个 eslint 规则。 (不是一个好主意);

      【讨论】:

        【解决方案4】:

        根据 Eslint 文档,使用这些运算符会自动插入分号,空格的差异会改变源代码的语义。

        所以在 eslint 规则中是不允许的,但是你可以使用这一行忽略它:

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

        参考 eslint 文档:https://eslint.org/docs/rules/no-plusplus

        【讨论】:

          【解决方案5】:

          eslint no-plusplus: "错误"

          将在以下实例中引发错误

          var foo = 0;
          foo++;
          
          var bar = 42;
          bar--;
          
          for (i = 0; i < l; i++) {
              return;
          }
          

          使用以下方法修复 lint 问题,使其符合规则

          var foo = 0;
          foo += 1;
          
          var bar = 42;
          bar -= 1;
          
          for (i = 0; i < l; i += 1) {
              return;
          }
          

          Documentation

          【讨论】:

            猜你喜欢
            • 2018-05-23
            • 2017-06-26
            • 1970-01-01
            • 2016-05-02
            • 2012-12-18
            • 2016-06-12
            • 2019-10-30
            • 2019-01-12
            相关资源
            最近更新 更多