我不喜欢这里的, ,
:
let colors = [ "red", "green", "blue" ];
let [ , , thirdColor] = colors;
我可以使用一些占位符吗?我不想引入未使用的变量,我只是想让代码看起来更清晰。现在,我唯一能想到的就是评论:
let [/*first*/, /*second*/, thirdColor] = colors;
还有更好的主意吗?
最佳答案
JS中没有占位符的概念。通常使用_
,但是实际上不能在一个声明中多次使用它:
let [_, secondColor] = colors; // OK
let [_, _, thirdColor] = colors; // error
另外,
_
实际上可能在您的代码中使用,因此您必须想出另一个名称,等等。最简单的方法可能是直接访问第三个元素:
let thirdColor = colors[2];
let {2: thirdColor, 10: eleventhColor} = colors;
关于javascript - 在es6数组解构中可以用作占位符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35086960/