javascript - 如何处理 Array.prototype.reduce() 函数中的 eslint no-param-reassign 规则

标签 javascript ecmascript-6 eslint

我最近添加了 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;
}, {});

有没有更好的方法来使用 reduce 构建一个不修改 accumulator 参数的对象?

或者我应该在我的 reduce 回调函数中禁用该行的 linting 规则?

最佳答案

我只是将reduce函数包装在lint规则禁用 block 中,即:

/* eslint-disable no-param-reassign */
const newObject = ['a', 'b', 'c'].reduce((result, item, index) => {
  result[item] = index;
  return result;
}, {});
/* eslint-enable no-param-reassign */

关于javascript - 如何处理 Array.prototype.reduce() 函数中的 eslint no-param-reassign 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41625399/

相关文章:

javascript - 在构造函数中初始化状态时出现意外标记

javascript - javascript中括号与 `this`绑定(bind)的效果

javascript - 将整个对象应用到另一个对象的简写?

javascript - ES6早期使用类

javascript - 使用 `--fix` 标志自动化 ESLint 会产生哪些问题?

javascript - Jquery 每个选择器与类选择器

Javascript通过对象的属性过滤对象数组

javascript - 带有 ECMAScript 6 类的命名空间

Eslint 填充 block : ["error", { "blocks": "never"}] 不起作用

javascript - 是否可以在通过表单上传之前预览本地镜像?