代码之家  ›  专栏  ›  技术社区  ›  Ralph David Abernathy

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

  •  0
  • Ralph David Abernathy  · 技术社区  · 3 年前

    我有以下变量:

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

    [$firstSection] = $main.children;

    但是,我应该如何对第二个变量使用数组反结构呢?谢谢。

    2 回复  |  直到 3 年前
        1
  •  1
  •   CertainPerformance    3 年前

    只需将第二个要解构的项放在第一个项的右侧,以逗号分隔的列表中。它看起来非常类似于声明一个包含2个项的数组。

    const [$firstSection, $secondSection] = $main.children;
    
        2
  •  1
  •   cmprogram    3 年前

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

     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