如何使用 Airbnb JavaScript 风格更新数组中的所有项目?
假设我们有一个这样的数组:
let list = [
{
name: '1',
count: 0,
},
{
name: '2',
count: 10,
},
{
name: '3',
count: 18,
},
];
那么如何更新所有项目以使 count
加 1?
这里有几个解决方案,但没有一个是令人满意的:
/* no-restricted-syntax error, pass */
for (const item of list) {
item.count += 1;
}
/* no-param-reassign error, pass */
list.forEach((item) => {
item.count += 1;
});
/*
Object.assign is free to use without error
but it against the intention of no-param-reassign
*/
list.forEach((item) => {
Object.assign(item, { count: item.count + 1 });
});
/*
use Array.map() to replace the original array
but it costs a lot when the item is large or the array has a large length
also ugly code for such a tiny update
*/
list = list.map((item) => ({
...item,
count: item.count + 1,
}));
如果您有更好的解决方案或认为Array.map()
足够好,请留下您的意见。
谢谢 :)
Let's say that we have an array like this:
let list = [
{
name: '1',
count: 0,
},
{
name: '2',
count: 10,
},
{
name: '3',
count: 18,
},
];
Then how to update all items to increase count
by 1?
Here comes several solutions, while none of them is quite satisfactory:
/* no-restricted-syntax error, pass */
for (const item of list) {
item.count += 1;
}
/* no-param-reassign error, pass */
list.forEach((item) => {
item.count += 1;
});
/*
Object.assign is free to use without error
but it against the intention of no-param-reassign
*/
list.forEach((item) => {
Object.assign(item, { count: item.count + 1 });
});
/*
use Array.map() to replace the original array
but it costs a lot when the item is large or the array has a large length
also ugly code for such a tiny update
*/
list = list.map((item) => ({
...item,
count: item.count + 1,
}));
If you have a better solution or consider Array.map()
is good enough, please leave your opinion.
Thank you :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通常使用普通循环以避免Airbnb棉绒问题如下:
I generally use normal for loop to avoid Airbnb lint issue as follow: