问题描述
我最近添加了eslint规则 no-param-reassign 代码>
.
但是,当我使用 reduce
构建一个对象(空对象为 initialValue
),我发现自己需要修改 accumulator
(回调函数的第一个参数)在每次回调迭代中,都会引起 no-param-reassign
短绒投诉(就像人们期望的那样).
const newObject = ['a','b','c'].reduce((result,item,index)=> {结果[项目] =索引;//<-引起无参数重新分配投诉返回结果;},{});
是否有更好的方法来构建不修改 accumulator
参数的 reduce
对象?
还是我应该在我的 reduce
回调函数中直接禁用该行的掉毛规则?
每当我使用 Array.prototype.reduce
时,我总是将其命名为累加器".参数 accu
.该约定方便地允许我设置自己的陪同规则:
如果您对此参数有自己的命名约定,请替换为"accu".在上面的规则中,无论使用什么,eslint都不会抱怨修改累加器.
I've recently added the eslint rule 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).
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?
Or should I simply disable the linting rule for that line in my reduce
callback functions?
Whenever I use Array.prototype.reduce
I always name the "accumulator" parameter accu
. This convention conveniently allowed me to set my eslint rule:
"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.
这篇关于如何在Array.prototype.reduce()函数中处理eslint无参数重新分配规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!