如何使用 Airbnb JavaScript 风格更新数组中的所有项目?

发布于 2025-01-18 05:02:19 字数 1050 浏览 3 评论 0原文

假设我们有一个这样的数组:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眉黛浅 2025-01-25 05:02:19

我通常使用普通循环以避免Airbnb棉绒问题如下:

for (let index = 0; index < list.lenght; index++) {
    const item = list[index];
    if (item) {
        item.count += 1;
    }
}

I generally use normal for loop to avoid Airbnb lint issue as follow:

for (let index = 0; index < list.lenght; index++) {
    const item = list[index];
    if (item) {
        item.count += 1;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文