我正在运行 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/