[js] 구조 분해 할당

·2022년 1월 10일
0

공부한 것

목록 보기
15/58

배열, 객체 분해하기

  • 객체나 배열을 변수로 분해 할 수 있게 해주는 문법
  • 함수의 매개변수가 많거나 매개변수 기본값이 필요한 경우 유용
let arr = ['Bora', 'Lee']

let [fistName, surname] = arr;

alert(firstName); // Bora
alert(surname);  // Lee

//------------------------------------------------------------------------

let {var1, var2} = {var1:, var2:}
let {title, width, height} = options;
// let {...} 안의 순서가 바뀌어도 동일하게 동작함 - 키를 찾아서 그런 듯
let {height, width, title} = { title: "Menu", height: 200, width: 100 }
let [firstName, surname] = "Bora Lee".split(' ');
//가능
  • 원본은 파괴되지 않는다 변수로 재할당하는 과정이 줄어드는 것 뿐
  • 필요없는 요소는 가져오지 않는 방법
// 두 번째 요소는 필요하지 않음
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
//Caesar은 ,,라서 무시된 것이고
//of the Roman Republic은 할당할 변수가 없어서 안된 것

alert( title ); // Consul
  • 모든 이터러블은 구조 분해가능하다
  • 배열, 객체, 변수 뭐든지 할당받는 것이 가능
let user = {};
[user.name, user.surname] = "Bora Lee".split(' ');

alert(user.name); // Bora
  • 변수 교환 트릭(swap)
    • 이 방식을 사용하면 두 개 이상의 변수에 담긴 값도 교환할 수 있다
let guest = "Jane";
let admin = "Pete";

// 변수 guest엔 Pete, 변수 admin엔 Jane이 저장되도록 값을 교환함
[guest, admin] = [admin, guest];

alert(`${guest} ${admin}`); // Pete Jane(값 교환이 성공적으로 이뤄졌습니다!)
  • 스프레드 연산자를 사용한 구조 분해
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];

alert(name1); // Julius
alert(name2); // Caesar

// `rest`는 배열입니다.
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2
  • 구조 분해도 일반 변수와 동일하게 동작해서 할당값이 없으면 undefined가 할당되고 기본값을 설정할 수 있다.
  • 객체를 구조 분해 할 때 변수명을 객체의 키와 다른 이름으로 사용하는 방법
let options = {
  title: "Menu",
  width: 100,
  height: 200
};

// { 객체 프로퍼티: 목표 변수 }
let {width: w, height: h, title} = options;

// width -> w
// height -> h
// title -> title

alert(title);  // Menu
alert(w);      // 100
alert(h);      // 200
  • 선언된 변수를 이용하기 - ()쳐주기
  • {}를 블록으로 인식해서 선언을 하지않고 {}를 썼다고 오류남
let title, width, height;

// SyntaxError: Unexpected token '=' 이라는 에러가 아랫줄에서 발생합니다.
{title, width, height} = {title: "Menu", width: 200, height: 100};

//------------------------------------------------------------------------

let title, width, height;

// 에러가 발생하지 않습니다.
({title, width, height} = {title: "Menu", width: 200, height: 100});

alert( title ); // Menu

중첩 구조 분해

let options = {
  size: {
    width: 100,
    height: 200
  },
  items: ["Cake", "Donut"],
  extra: true
};

// 코드를 여러 줄에 걸쳐 작성해 의도하는 바를 명확히 드러냄
let {
  size: { // size는 여기,
    width,
    height
  },
  items: [item1, item2], // items는 여기에 할당함
  title = "Menu" // 분해하려는 객체에 title 프로퍼티가 없으므로 기본값을 사용함
} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200
alert(item1);  // Cake
alert(item2);  // Donut

매개변수에 구조 분해 사용하기

// 함수에 전달할 객체
let options = {
  title: "My menu",
  items: ["Item1", "Item2"]
};

// 똑똑한 함수는 전달받은 객체를 분해해 변수에 즉시 할당함
function showMenu({title = "Untitled", width = 200, height = 100, items = []}) {
  // title, items – 객체 options에서 가져옴
  // width, height – 기본값
  alert( `${title} ${width} ${height}` ); // My Menu 200 100
  alert( items ); // Item1, Item2
}

showMenu(options);

//------------------------------------------------------------------------

let options = {
  title: "My menu",
  items: ["Item1", "Item2"]
};

function showMenu({
  title = "Untitled",
  width: w = 100,  // width는 w에,
  height: h = 200, // height는 h에,
  items: [item1, item2] // items의 첫 번째 요소는 item1에, 두 번째 요소는 item2에 할당함
}) {
  alert( `${title} ${w} ${h}` ); // My Menu 100 200
  alert( item1 ); // Item1
  alert( item2 ); // Item2
}

showMenu(options);

//------------------------------------------------------------------------

showMenu({}); // 모든 인수에 기본값이 할당됩니다. -> 명시적으로 객체를 전달해 줘야한다

showMenu(); // 에러가 발생할 수 있습니다.

무슨말인지 모르겠는 부분

  • .entries()로 반복하기
    • 이 메서드와 구조 분해를 조합하면 객체의 키와 값을 순회해 변수로 분해 할당할 수 있습니다.
let user = {
  name: "John",
  age: 30
};

// 객체의 키와 값 순회하기
for (let [key, value] of Object.entries(user)) {
  alert(`${key}:${value}`); // name:John, age:30이 차례대로 출력
}

//------------------------------------------------------------------------

let user = new Map();
user.set("name", "John");
user.set("age", "30");

for (let [key, value] of user) {
  alert(`${key}:${value}`); // name:John, then age:30
}

참고자료

모던 javascript 튜토리얼 - 구조 분해 할당

0개의 댓글