Деструктуризация массива JavaScript: методы и примеры

Чтобы деструктурировать массив в JavaScript, вы можете использовать несколько методов. Вот несколько часто используемых методов:

  1. Деструктуризация массива:

    const array = [1, 2, 3];
    const [a, b, c] = array;
    console.log(a); // Output: 1
    console.log(b); // Output: 2
    console.log(c); // Output: 3
  2. Пропуск элементов:

    const array = [1, 2, 3, 4, 5];
    const [, , c, , e] = array;
    console.log(c); // Output: 3
    console.log(e); // Output: 5
  3. Схема отдыха:

    const array = [1, 2, 3, 4, 5];
    const [a, ...rest] = array;
    console.log(a);     // Output: 1
    console.log(rest);  // Output: [2, 3, 4, 5]
  4. Значения по умолчанию:

    const array = [1];
    const [a, b = 2] = array;
    console.log(a); // Output: 1
    console.log(b); // Output: 2 (default value)
  5. Замена переменных:

    let a = 1;
    let b = 2;
    [a, b] = [b, a];
    console.log(a); // Output: 2
    console.log(b); // Output: 1

Это всего лишь несколько примеров деструктуризации массивов в JavaScript. Используя эти методы, вы можете легко извлекать значения из массива и присваивать их переменным.