如何避免 Airbnb ESLint 中的 "Arrow function expect to return a value" 错误
How to avoid "Arrow function expect to return a value" error in Airbnb ESLint
我是运行 eslint,建议在使用箭头函数(lambda函数)时return一个值。好吧,这是有道理的。然而,我遇到了一个难以走动的案例。
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 之外,是否有任何迭代工具或函数可以帮助我实现目标并避免违反规则?
使用 forEach
而不是 map
。
map
的重点是修改数组中的每一项,并将修改后的版本放入新数组中。
forEach
只是对每个项目运行一个函数。
编辑:这不遵守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://whosebug.com' }
]
const result = instances.reduce((dict, item) => {
dict[item.name] = item.url
return dict
}, {})
console.log(result)
为什么不 .map?
Array.map
总是 returns 一个新的 Array
并且用于将每个数组元素映射到另一种格式。
如果生成的数据结构不应该是 Array
,并且长度与您正在操作的 Array
相同,则应避免使用它。
为什么 .reduce 而不是 .forEach?
我使用 forEach
只是为了做 "work" 而不是转换数据。只需 map
and/or reduce
.
几乎总是可以实现数据转换
我的意思是 "work":
const users = [userInstance, userInstance, userInstance]
users.forEach(user => user.sendEmail('Hello World'))
如果您正在寻找 ES6 解决方案来填充字典对象,这可能会有所帮助并且也应该通过 ESLint:-
const dict = Instances.reduce((map, obj) => (map[obj.name] = obj.url, map), {});
更新
const dict = Instances.reduce((map, obj) => {
let mapClone = {};
mapClone = Object.assign({}, map);
mapClone[obj.name] = obj.url;
return mapClone;
}, {});
我是运行 eslint,建议在使用箭头函数(lambda函数)时return一个值。好吧,这是有道理的。然而,我遇到了一个难以走动的案例。
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 之外,是否有任何迭代工具或函数可以帮助我实现目标并避免违反规则?
使用 forEach
而不是 map
。
map
的重点是修改数组中的每一项,并将修改后的版本放入新数组中。
forEach
只是对每个项目运行一个函数。
编辑:这不遵守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://whosebug.com' }
]
const result = instances.reduce((dict, item) => {
dict[item.name] = item.url
return dict
}, {})
console.log(result)
为什么不 .map?
Array.map
总是 returns 一个新的 Array
并且用于将每个数组元素映射到另一种格式。
如果生成的数据结构不应该是 Array
,并且长度与您正在操作的 Array
相同,则应避免使用它。
为什么 .reduce 而不是 .forEach?
我使用 forEach
只是为了做 "work" 而不是转换数据。只需 map
and/or reduce
.
我的意思是 "work":
const users = [userInstance, userInstance, userInstance]
users.forEach(user => user.sendEmail('Hello World'))
如果您正在寻找 ES6 解决方案来填充字典对象,这可能会有所帮助并且也应该通过 ESLint:-
const dict = Instances.reduce((map, obj) => (map[obj.name] = obj.url, map), {});
更新
const dict = Instances.reduce((map, obj) => {
let mapClone = {};
mapClone = Object.assign({}, map);
mapClone[obj.name] = obj.url;
return mapClone;
}, {});