简体   繁体   English

如何在索引不为 0 的 Javascript 数组上使用数组解构?

[英]How to use array destructuring on Javascript array with index of not 0?

I have the following variables:我有以下变量:

$firstSection = $main.children[0];
$secondSection = $main.children[1];

To use array destructuring on the first variable, I can do this: [$firstSection] = $main.children;要对第一个变量使用数组解构,我可以这样做: [$firstSection] = $main.children;

However, how am I supposed to use array destructuring on the second variable?但是,我应该如何对第二个变量使用数组解构? Thanks.谢谢。

Just put the second item to destructure to the right of the first, in a comma-separated list.只需将要解构的第二个项目放在第一个项目的右侧,以逗号分隔的列表。 It looks very similar to when declaring an array with 2 items.它看起来与声明包含 2 个项目的数组时非常相似。

const [$firstSection, $secondSection] = $main.children;

The values are accessed through a comma separated list, so:这些值通过逗号分隔的列表访问,因此:

 const [$firstSection, $secondSection] = $main.children; 
 console.log($secondSection); // The second value in the $main.children array

And if you actually don't need the first value in the array, for whatever reason - you can actually just use a comma to omit the first value.如果您实际上不需要数组中的第一个值,无论出于何种原因 - 您实际上可以使用逗号来省略第一个值。

const [, $secondSection] = $main.children;
console.log($secondSection); // The second value in the $main.children array

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

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