我最近添加了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;
}, {});
字符串
有没有更好的方法来构建一个不修改accumulator
参数的reduce
对象?
或者我应该简单地在我的reduce
回调函数中禁用该行的linting规则?
5条答案
按热度按时间yqkkidmi1#
我只是将reduce函数 Package 在lint rule disable块中,即:
字符串
yhqotfr82#
一种解决方案是利用object spread operator
字符串
**性能警告!!**这是应该避免的non-performant (
O(n^2
) solution。rur96b6h3#
每当我使用
Array.prototype.reduce
时,我总是将“累加器”参数命名为accu
。这个约定方便了我设置eslint规则:字符串
如果你有自己的命名规则,那么把上面规则中的“accu”替换为你所使用的任何东西,eslint就不会抱怨修改累加器了。
mepcadol4#
好吧,你可以执行
(result, item) => Object.assign({}, result, {[item]: whatever})
来在每次迭代中创建一个新对象:-)如果你想欺骗linter,你可以使用
=> Object.assign(result, {[item]: whatever})
(它和你当前的代码一样,但是没有显式的赋值),但是我想你应该简单地禁用那个规则。i34xakig5#
由于我找不到其他合理的解决方案,我只是禁用了这一检查:
字符串