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

How to handle eslint no-param-reassign rule in Array.prototype.reduce() functions

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

然而,当我使用 reduce 构建一个对象(空对象如 initialValue)时,我发现自己需要修改 accumulator(回调函数的第一个参数)在每次回调迭代中,这会导致 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 规则?

好吧,您可以 (result, item) => Object.assign({}, result, {[item]: whatever}) 在每次迭代时创建一个新对象 :-)

如果你想欺骗 linter,你可以使用 => Object.assign(result, {[item]: whatever})(它与你当前的代码相同,但没有明确的分配),但是我想你应该简单地禁用该规则。

一个解决方案是利用 object spread operator

const newObject = ['a', 'b', 'c'].reduce((result, item, index) => ({
  ...result,
  [item]: index, 
}), {});

性能警告!!这是一个应该避免的non-performant (O(n^2) solution

我只是将 reduce 函数包装在一个 lint 规则禁用块中,即:

/* eslint-disable no-param-reassign */
const newObject = ['a', 'b', 'c'].reduce((result, item, index) => {
  result[item] = index;
  return result;
}, {});
/* eslint-enable no-param-reassign */

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

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

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