我最近添加了 eslint 规则 no-param-reassign
。
但是,当我使用 reduce
构建对象(空对象 initialValue
)时,我发现自己需要修改 accumulator
g-of-first 函数) 在每次回调迭代中,这会导致 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 规则?
原文由 sfletche 发布,翻译遵循 CC BY-SA 4.0 许可协议
每当我使用
Array.prototype.reduce
时,我总是将“累加器”参数命名为accu
。这个约定方便地让我设置我的 eslint 规则:如果您对此参数有自己的命名约定,请将上面规则中的“accu”替换为您使用的任何内容,eslint 将不会抱怨修改您的累加器。