简体   繁体   English

ESLint 如何应用“使用数组解构”?

[英]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)".我的项目配置了 ESLint 的 AirBnb 规则,它抛出以下错误:“使用数组解构(首选解构)”。

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?但是,我看到两个问题:1. 它很难看(在我看来很难阅读)和 2. 如果我试图访问数组的第 20 个元素,我是否必须使用 20 个逗号?

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?但是,我看到两个问题:1. 它很难看(在我看来很难阅读)和 2. 如果我试图访问数组的第 20 个元素,我是否必须使用 20 个逗号?

I agree it's ugly, and yes you'd need 20 commas to access element 20 on its own.我同意这很丑陋,是的,您需要 20 个逗号才能单独访问元素 20。 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:在你的eslint.rc文件中:

{
  "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.如果完全关闭它比你想要的更多(比如,你想为对象保留它,但为数组关闭它),你可以在你的 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.在这里, 20是一个键,因为数组本质上只是带有方法的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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