javascript - 如何避免 Airbnb ESLint 中的 "Arrow function expect to return a value"错误

标签 javascript arrow-functions eslint-config-airbnb

我正在运行 eslint,建议在使用箭头函数(lambda 函数)时返回一个值。嗯,这是有道理的。然而,我遇到了一个很难走动的案例。

Dict = {}
Instances = [/* an array of items where items is a dictionary that contains data */]
Instances.map((item) => {
      Dict[item.name] = item.url;
});

我的目标是从 Instances 数组中获取数据并用它填充字典 Dict。我使用数组函数将键值对分配给字典,但这违反了箭头函数的规则。

除了map之外,是否有任何迭代工具或函数可以帮助我实现目标,并避免违反规则?

最佳答案

编辑:遵守 Airbnb's ES6 Style Guide .

<小时/>

My goal is to get the data from the Instances array and fill the dictionary with it.

使用.reduce

.. 只需传递一个空对象作为累加器,在迭代数组时将其填充。

const instances = [
 { name: 'foo', url: 'https://google.com' }, 
 { name: 'bar', url: 'https://stackoverflow.com' }
]

const result = instances.reduce((dict, item) => {
  dict[item.name] = item.url

  return dict
}, {})

console.log(result)

为什么不.map

Array.map 始终返回一个新的 Array,用于将每个数组元素映射到另一种格式。

如果您生成的数据结构不应该是 Array,且其长度与您正在操作的 Array 相同,则应避免使用它。

为什么 .reduce而不是.forEach

我使用forEach仅用于“工作”而不是转换数据。转换数据几乎总是可以通过 map 和/或 reduce 来实现。

这就是我所说的“工作”:

const users = [userInstance, userInstance, userInstance]
users.forEach(user => user.sendEmail('Hello World'))

关于javascript - 如何避免 Airbnb ESLint 中的 "Arrow function expect to return a value"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162857/

相关文章:

javascript - 在 elementor 上 lottie 动画结束后离开页面

javascript - typescript :匿名函数中可能 undefined variable

javascript - 数组 forEach() 与 reduce()

javascript - 在 javascript 中搜索对象数组中的重复字符串

javascript - jQuery promise 是否符合 Promises/A+

javascript - HTML/JS Canvas Donut Chart 如何创建重叠的圆形笔划?

memory-management - 在 CoffeeScript 中构建类时,是否有理由不使用实例方法的粗箭头?

javascript - 如何将箭头函数 (=>) 的结果分配给 JavaScript 中的变量

javascript - ESLint : Spacing around equal sign

reactjs - 如何设置高阶函数组件的 PropTypes?