简体   繁体   English

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

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

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?那么如何更新所有项目以将count增加 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.如果您有更好的解决方案或认为Array.map()足够好,请留下您的意见。

Thank you:)谢谢:)

I generally use normal for loop to avoid Airbnb lint issue as follow:我通常使用正常的 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.

相关问题 如何使用 Airbnb JavaScript 风格指南设置 Prettier - How do I set up Prettier with Airbnb JavaScript Style Guide 如何运行Airbnb javascript样式指南中的代码? - How do I run the code in the Airbnb javascript style guide? 如何更新 Angular 中使用 *ngFor 迭代的所有项目的样式 - How to update the style of all the items which are iterated using *ngFor in Angular 如何使Airbnb的JavaScript样式eslint指南与React,ES6一起在vim中工作? - How to get Airbnb's JavaScript style eslint guide working in vim with react, es6? 带有 Airbnb 风格指南的 ESLint 不适用于所有规则 - ESLint with Airbnb style guide does not work for all rules PolymerJS:如何正确使用set()和forEach循环更新数组中的所有项目 - PolymerJS: How to Update all Items in an Array with set() and a forEach loop properly 通过解构或forEach进行缩减-迭代和Airbnb JavaScript样式指南 - Reduce with deconstruction or forEach - Iteration and Airbnb JavaScript Style Guide 如何使用jQuery将节点的所有子节点作为javascript中的数组项 - how to get all the children of a node as items of an array in javascript using jQuery 如何将Javascript OBJECT / JSON中的所有项目分离到数组中 - How to seperate all items in a Javascript OBJECT / JSON to a array 如何在JavaScript中以线性顺序从数组中减去所有项目? - How to subtract all items from an array in linear order in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM