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

How to update all items in an Array with Airbnb JavaScript Style?

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

let list = [
  {
    name: '1',
    count: 0,
  },
  {
    name: '2',
    count: 10,
  },
  {
    name: '3',
    count: 18,
  },
];

那如何更新所有的项目,让count增加1?

这里有几个解决方案,其中none个比较满意:

/* 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()已经足够好了,请留下您的意见。

谢谢:)

我通常使用正常的 for 循环来避免如下 Airbnb lint 问题:

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