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

问题描述 投票:0回答:6

我最近添加了 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 规则?

javascript ecmascript-6 eslint
6个回答
36
投票

我只是将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 */

34
投票

一种解决方案是利用 对象扩展运算符

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

性能警告!!这是应该避免的非性能(

O(n^2
)解决方案


31
投票

每当我使用

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

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

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


11
投票

好吧,你可以做

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

如果你想欺骗 linter,你可以使用

=> Object.assign(result, {[item]: whatever})
(它与你当前的代码相同,但没有显式分配),但是是的,我想你应该简单地禁用该规则。


1
投票

由于我没有找到其他合理的解决方案,所以我只是禁用该单一检查:

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

0
投票

有一个选项“ignorePropertyModificationsForRegex”来配置它:

"rules": {
  "no-param-reassign": [
    "error",
    { "props": true, "ignorePropertyModificationsForRegex": ["acc"] }
  ],
© www.soinside.com 2019 - 2024. All rights reserved.