如何在索引不是0的Javascript数组上使用数组析构函数



我有以下变量:

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

要对第一个变量使用数组析构函数,我可以这样做:[$firstSection] = $main.children;

然而,我应该如何对第二个变量使用数组析构函数呢?谢谢

只需将第二个要销毁的项放在第一个项的右侧,以逗号分隔。它看起来与声明一个包含2个项的数组非常相似。

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

通过逗号分隔的列表访问值,因此:

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

如果您实际上不需要数组中的第一个值,无论出于何种原因,您实际上可以使用逗号来省略第一个值。

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

最新更新