[英]How to handle eslint no-param-reassign rule in Array.prototype.reduce() functions
I've recently added the eslint rule no-param-reassign
.我最近添加了 eslint 规则
no-param-reassign
。
However, when I use reduce
to build out an object (empty object as initialValue
), I find myself needing to modify the accumulator
(first arg of callback function) on each callback iteration, which causes a no-param-reassign
linter complaint (as one would expect it would).但是,当我使用
reduce
构建一个对象(空对象作为initialValue
)时,我发现自己需要在每次回调迭代时修改accumulator
(回调函数的第一个 arg),这会导致no-param-reassign
linter 投诉(如人们会期望它会)。
const newObject = ['a', 'b', 'c'].reduce((result, item, index) => {
result[item] = index; // <-- causes the no-param-reassign complaint
return result;
}, {});
Is there a better way to build out an object with reduce
that doesn't modify the accumulator
argument?有没有更好的方法来构建一个不修改
accumulator
参数的reduce
对象?
Or should I simply disable the linting rule for that line in my reduce
callback functions?或者我应该在我的
reduce
回调函数中简单地禁用该行的linting规则?
One solution would be to leverage the object spread operator一种解决方案是利用对象扩展运算符
const newObject = ['a', 'b', 'c'].reduce((result, item, index) => ({
...result,
[item]: index,
}), {});
Performance Warning!!性能警告!! This is a non-performant (
O(n^2
) solution that should be avoided.这是应该避免的非性能(
O(n^2
) 解决方案。
I just wrap the reduce functions in a lint rule disable block, ie:我只是将 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 */
Well, you could do (result, item) => Object.assign({}, result, {[item]: whatever})
to create a new object on every iteration :-)好吧,你可以做
(result, item) => Object.assign({}, result, {[item]: whatever})
在每次迭代时创建一个新对象:-)
If you want to trick the linter, you could use => Object.assign(result, {[item]: whatever})
(which does the same as your current code but without an explicit assignment), but yeah I guess you should simply disable that rule.如果你想欺骗 linter,你可以使用
=> Object.assign(result, {[item]: whatever})
(它和你当前的代码一样,但没有明确的赋值),但是我想你应该简单地禁用该规则。
Whenever I use Array.prototype.reduce
I always name the "accumulator" parameter accu
.每当我使用
Array.prototype.reduce
我总是将“累加器”参数命名为accu
。 This convention conveniently allowed me to set my eslint rule:这个约定方便我设置我的 eslint 规则:
"no-param-reassign": [
"error",
{
"props": true,
"ignorePropertyModificationsFor": ["accu"]
}
],
If you have your own naming convention for this parameter, replace "accu" in the rule above with whatever you use, and eslint will not complain about modifying your accumulator.如果您对此参数有自己的命名约定,请将上面规则中的“accu”替换为您使用的任何内容,并且 eslint 不会抱怨修改您的累加器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.