簡體   English   中英

如何使用 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?

這里有幾個解決方案,但沒有一個是令人滿意的:

/* 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM