最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to destructure only the first index of an array - Stack Overflow

programmeradmin6浏览0评论

ESLint gives an error for link = link.split("?")[0]. It says to use array destructuring. But if i use array destructuring, then the code will be

let [ temp ] = link.split("?");
link = temp;

This results in the use of an extra variable. Is there another way to do it without creating an extra variable and avoiding the ESLint error. Thank You.

ESLint gives an error for link = link.split("?")[0]. It says to use array destructuring. But if i use array destructuring, then the code will be

let [ temp ] = link.split("?");
link = temp;

This results in the use of an extra variable. Is there another way to do it without creating an extra variable and avoiding the ESLint error. Thank You.

Share Improve this question asked Dec 16, 2018 at 15:48 kryptokinghtkryptokinght 5595 silver badges13 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

But if i use array destructuring, then the code will be...

You can destructure into an existing variable, you don't have to declare a new one. So instead, it would be:

[link] = link.split("?");

Live Example:

let link = "testing?one?two";
[link] = link.split("?");
console.log(link);

On occasion (for instance, when using object destructuring), you need parentheses to avoid parsing confusion:

let link;
let obj = {
    link: "example"
};
({link} = obj);
console.log(link);

Other times, if you like to rely on Automatic Semicolon Insertion rather than typing semicolons where they're required, you'll need the ; when doing array destructuring without a declaration. This is an error:

// Hazard if relying on ASI
let link = "testing?one?two?"
console.log("hi there")
[link] = link.split("?")
console.log(link)

Typically, the no-semicolon folks use a leading ; in this situation, e.g.:

;[link] = link.split("?")

You can do like this

With the help of array de-structuring.

let link = "hello?hahah";
[link] = link.split('?');
console.log(link);

Use .shift()

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

[link] = link.split("?");

T.J.'s answer is the what you are looking for,

but mutating variables is not the best way of writing code. On the other hand destructing is just a clean way of writing code. If you see the transpiled code for the destructing part, you will find that a new variable is being set.

on a side note, eslint can't force you to do anything, if you are that concerned about performance you can allow link = link.split("?")[0] to stand,

please disable your prefer-destructuring config inside your .eslintrc.json,

{   
  "rules": {
    "prefer-destructuring": ["error", {"object": false, "array": false}]   
  } 
}
发布评论

评论列表(0)

  1. 暂无评论