【问题标题】:Fix ESLint no-plusplus and no-param-reassign linter errors when adding to accumulator in reduce function在 reduce 函数中添加到累加器时修复 ESLint no-plusplus 和 no-param-reassign linter 错误
【发布时间】:2021-02-09 09:36:34
【问题描述】:

在 TypeScript 中给出这段代码:

const res = arr.reduce((acc, cur) => (cur.id ? ++acc : acc), 0);

如何阻止 linter 抛出这两个错误?

(参数)acc:使用数字一元运算符'++'。 eslint no-plusplus

分配给函数参数'acc'。 eslint no-param-reassign

【问题讨论】:

    标签: javascript typescript eslint


    【解决方案1】:

    reduce 回调接受一个累加器和当前值作为参数,并返回下一次迭代的累加器,如果没有下一次迭代,则返回累加器作为结果。没有理由改变任何论点。

    a few arguments in favor of avoiding mutating parameters in general,这就是 ESLint 抱怨这个的原因,no-param-reassign rule

    另外,no-plusplus rule 不允许使用像 ++acc 这样的语法。

    由于无需更改 acc 一开始,两个错误的最小修复是:

       const res = arr.reduce((acc, cur) => (cur.id ? acc + 1 : acc), 0);
    //                                                ~~~~^~~              Replace `++acc` by `acc + 1`
    

    如果cur.id 为真,则返回acc,增加1,否则返回当前acc,否则,如预期的那样。您的版本除了返回递增的acc 之外,还改变了当前的acc,但没有理由这样做。


    如果您使用 ESLint,则必须了解规则。你不能编写 ESLint 抱怨的代码,然后对 ESLint 抱怨你的代码的原因感到困惑。 Every rule 有自己的文章解释基本原理,列出替代方案,并解释如何调整或禁用规则。

    例如,您可以禁用no-param-reassign 规则

    • 通过在文件顶部添加评论 // eslint-disable no-param-reassign
    • // eslint-disable-next-line no-param-reassign在用法上方一行,
    • // eslint-disable-line no-param-reassign在一行使用后,
    • 或在您的 .eslintrc 文件中禁用它。

    还有a rule that would disallow conditional expressions 和一些variants。您可以进一步简化您的功能以避免:

    const res = arr.reduce((acc, cur) => acc + Number(Boolean(cur.id)), 0);
    

    这将具有相同的语义,但仍然不太清楚 cur.id 应该是什么样的条件。最好让它更明确一点(尤其是在 TypeScript 中),例如cur.hasOwnProperty("id")cur.id !== 0cur.id !== "",取决于 cur.id 可能是什么。然后,不再需要Boolean 调用;例如,如果您想计算 arr 中有多少对象拥有 id 属性,请改用它:

    const res = arr.reduce((acc, cur) => acc + Number(cur.hasOwnProperty("id")), 0);
    

    或者这个:

    const res = arr.filter((cur) => cur.hasOwnProperty("id")).length;
    

    如果您仍想使用原来的falsy / truthy 检查,代码可以缩短为其中之一,使用destructuring assignment

    const res = arr.reduce((acc, {id}) => acc + Number(Boolean(id)), 0);
    
    const res = arr.filter(({id}) => id).length;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-30
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 2016-01-08
      • 2018-05-23
      • 1970-01-01
      相关资源
      最近更新 更多