본문 바로가기

공부자료/자바스크립트

Section 9: Data Structures, ModernOperators and Strings - Destructuring Arrays

const [x, y, z] = arr;

arr는 detrcuturing를 원하는 Array

 

variable 이름에 [x, y, z] 는 array가 아니라 arr를 detructuring 해주는 것이다.

original arry에 아무런 영향을 주지 않는다.

const arr = [2, 4, 5]
const a = arr[0]
const b = arr[1]
const c = arr[2]

const [x, y ,z] = arr;

console.log(x, y z)

2 4 5


, , 건너뛰기

main과 secondary 순서 바꾸기

const restaurant = {
    name: 'Classico Italiano',
    location: 'Via Angelo Tavanti 23, Firenze, Italy',
    categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
    starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
    mainMenu: ['Pizza', 'Pasta', 'Risotto'],
  
    openingHours: {
      thu: {
        open: 12,
        close: 22,
      },
      fri: {
        open: 11,
        close: 23,
      },
      sat: {
        open: 0, // Open 24 hours
        close: 24,
      },
    },
  };

let [main, ,secondary] = restaurant.categories;
console.log(main, secondary);

[main, secondary] = [secondary, main]

const restaurant = {
    name: 'Classico Italiano',
    location: 'Via Angelo Tavanti 23, Firenze, Italy',
    categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
    starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
    mainMenu: ['Pizza', 'Pasta', 'Risotto'],
    order: function(starterIndex, mainIndex) {
        return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
    }
    openingHours: {
      thu: {
        open: 12,
        close: 22,
      },
      fri: {
        open: 11,
        close: 23,
      },
      sat: {
        open: 0, // Open 24 hours
        close: 24,
      },
    },
  };

let [main, ,secondary] = restaurant.categories;
console.log(main, secondary);

[main, secondary] = [secondary, main]


const [starter, mainFood] = (restaurant.order(2, 0))

console.log(starter, mainFood)

Garlic Bread, Pizza


const nested = [2, 4, [5, 6]];
const [i, ,j] = nested;
console.log(i, j)
  
const [i, ,[j, k]] = nested;
console.log(i, j, k);

2 [5, 6]

2, 5, 6


const [p, q, r] = [8, 9]
console.log(p, q, r)
// 8, 9, undefined

const [p = 1, q = 1, r =1] = [8, 9]
console.log(p, q, r)
// 8 ,9, 1 (default value)

default value 설정 가능