简体   繁体   中英

ESLint how to apply "Use array destructuring"?

Let's say I want to do something like this :

let foo = myArray[1];

My project being configured with ESLint's AirBnb rules, it throws the following error: "Use array destructuring (prefer-destructuring)".

I managed to solve the issue by doing :

let [, foo] = myArray;

However, I see two problems : 1. it's ugly (difficult to read in my opinion) and 2. what if I'm trying to access the 20th element of the array, will I have to use 20 commas?

The solution I found is obviously not viable, so is there a better way to solve the problem?

However, I see two problems : 1. it's ugly (difficult to read in my opinion) and 2. what if I'm trying to access the 20th element of the array, will I have to use 20 commas?

I agree it's ugly, and yes you'd need 20 commas to access element 20 on its own. If this is something you do once or twice, consider disabling the rule for that line.

// eslint-disable-next-line prefer-destructuring
let foo = myArray[20];

If it's something you do often, consider disabling the rule entirely. In your eslint.rc file:

{
  "rules": {
    "prefer-destructuring": "off",
  }
}

If turning it completely off is more than you want (say, you want to keep it for objects, but turn it off for arrays), you can add some different set of configs to your eslint.rc. You can see the various configuration options on this page

You can combine object literals and arrays to have

const {20: foo} = myArray;

Here, 20 is a key because arrays are just, in essence, objects with methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM