简体   繁体   English

我可以在es6数组解构中使用什么作为占位符?

[英]What can I use as placeholders in es6 array destructuring?

I don't like the , , here: 我不喜欢, ,在这里:

let colors = [ "red", "green", "blue" ];
let [ , , thirdColor] = colors;

Can I use some placeholders characters? 我可以使用一些占位符字符吗? I'd rather not introduce unused variables, I just want to make the code look clearer. 我宁愿不介绍未使用的变量,我只想让代码看起来更清晰。 Right now the only thing I can think about are comments: 现在我唯一可以考虑的是评论:

let [/*first*/, /*second*/, thirdColor] = colors;

Any better ideas? 有更好的想法吗?

There is no concept of a placeholder in JS. JS中没有占位符的概念。 Often _ is used for this, but you can't actually use it more than once in one declaration: 通常使用_ ,但实际上你不能在一个声明中多次使用它:

let [_, secondColor] = colors; // OK
let [_, _, thirdColor] = colors; // error

Also, _ may actually be used in your code, so you'd have to come up with another name, etc. 此外, _实际上可能会在您的代码中使用_ ,因此您必须提出其他名称等。

The simplest way may be to access the third element directly: 最简单的方法可能是直接访问第三个元素:

let thirdColor = colors[2];
let {2: thirdColor, 10: eleventhColor} = colors;

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

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