如何处理 Array.prototype.reduce() 函数中的 eslint no-param-reassign 规则

新手上路,请多包涵

我最近添加了 eslint 规则 no-param-reassign

但是,当我使用 reduce 构建对象(空对象 initialValue )时,我发现自己需要修改 accumulator g-of-first 函数) 在每次回调迭代中,这会导致 no-param-reassign linter 投诉(正如人们所期望的那样)。

 const newObject = ['a', 'b', 'c'].reduce((result, item, index) => {
  result[item] = index; // <-- causes the no-param-reassign complaint
  return result;
}, {});

有没有更好的方法来构建一个对象 reduce 不修改 accumulator 参数?

或者我应该在我的 reduce 回调函数中简单地禁用该行的 linting 规则?

原文由 sfletche 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 995
2 个回答

每当我使用 Array.prototype.reduce 时,我总是将“累加器”参数命名为 accu 。这个约定方便地让我设置我的 eslint 规则:

     "no-param-reassign": [
      "error",
      {
        "props": true,
        "ignorePropertyModificationsFor": ["accu"]
      }
    ],

如果您对此参数有自己的命名约定,请将上面规则中的“accu”替换为您使用的任何内容,eslint 将不会抱怨修改您的累加器。

原文由 Anj 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题