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 规则?
我只是将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 */
每当我使用
Array.prototype.reduce
时,我总是将“累加器”参数命名为 accu
。这个约定方便我设置我的 eslint 规则:
"no-param-reassign": [
"error",
{
"props": true,
"ignorePropertyModificationsFor": ["accu"]
}
],
如果您对此参数有自己的命名约定,请将上面规则中的“accu”替换为您使用的任何内容,eslint 不会抱怨修改您的累加器。
好吧,你可以做
(result, item) => Object.assign({}, result, {[item]: whatever})
在每次迭代中创建一个新对象:-)
如果你想欺骗 linter,你可以使用
=> Object.assign(result, {[item]: whatever})
(它与你当前的代码相同,但没有显式分配),但是是的,我想你应该简单地禁用该规则。
由于我没有找到其他合理的解决方案,所以我只是禁用该单一检查:
const newObject = ['a', 'b', 'c'].reduce((result, item, index) => {
// eslint-disable-next-line no-param-reassign
result[item] = index;
return result;
}, {});
有一个选项“ignorePropertyModificationsForRegex”来配置它:
"rules": {
"no-param-reassign": [
"error",
{ "props": true, "ignorePropertyModificationsForRegex": ["acc"] }
],