배열 분해하기
// 이름과 성을 요소로 가진 배열
let arr = ["Bora", "Lee"]
// 구조 분해 할당을 이용해
// firstName엔 arr[0]을
// surname엔 arr[1]을 할당하였습니다.
let [firstName, surname] = arr;
console.log(firstName); // Bora
console.log(surname); // Lee
반환 값이 배열 메서드인 split() 함수 일땐
let [firstName, surname] = "Bora Lee".split(' ');
쉼표를 사용하여 요소 무시하기
쉼표를 사용하면 필요하지 않은 배열 요소를 버릴 수 있습니다.
// 두 번째 요소는 필요하지 않음
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
console.log( title ); // Consul
할당 연산자 우측엔 모든 이터러블이 올 수 있습니다.
배열뿐만 아니라 모든 이터러블(iterable, 반복 가능한 객체)에 구조 분해 할당을 적용할 수 있습니다.
let [a, b, c] = "abc" // ["a", "b", "c"]
let [one, two, three] = new Set([1,2,3]);
할당 연산자 좌측엔 뭐든지 올 수 있습니다.
할당 연산자 좌측엔 '할당할 수 있는(assignables)' 것이라면 어떤 것이든 올 수 있습니다.
let user = {};
[user.name, user.surname] = "Bora Lee".split(' ');
alert(user.name); // Bora
.entries()로 반복하기
이 메서드와 구조 분해를 조합하면 객체의 키와 값을 순회해 변수로 할당 할 수 있습니다.
let user = {
name: "Jane",
age : 30
};
//객체의 키와 값 순회하기
for(let [key, value] of object.entries(user)){
console.log(`${key}:${value}`);
}
map() 메서드에도 적용할 수 있습니다.
let user = new Map();
user.set("name","John");
user.st("age","30");
for(let [key,value] of user){
console.log(`${key}:${value}`);
}
변수 교환 트릭
두 변수에 저장된 값을 교환할 때 구조 분해 할당을 사용할 수 있습니다.
let guest = "Jane";
let admin = "Pete";
// 변수 guest엔 Pete, 변수 admin엔 Jane이 저장되도록 값을 교환함
[guest, admin] = [admin, guest];
console.log(`${guest} ${admin}`); // Pete Jane
'...'로 나머지 요소 가져오기
배열 앞쪽에 위치한 값 몇 개만필요하고 그이후 이어지는 나머지 값들은 한데 모아서 저장하고 싶을 때가 있습니다. 이럴 때는 점 세개
...를 붙인 매개변수 하나를 추가하면 '나머지(rest)' 요소를 가져올 수 있습니다.
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
console.log(name1); // Julius
console.log(name2); // Caesar
// `rest`는 배열입니다.
console.log(rest[0]); // Consul
console.log(rest[1]); // of the Roman Republic
console.log(rest.length); // 2
rest는 나머지 배열 요소들이 저장된 새로운 배열이 됩니다. rest 대신에 다른 이름을 사용해도 되는데, 변수 앞의 점 세개(...)와 변수가 가장 마지막에 위치해야 한다는 점은 지켜주시기 바랍니다.
객체 분해하기
구조 분해 할당으로 객체도 분해할 수 있습니다.
let {var1, var2} = {var1:...,var2:...}
할당 연산자 우측엔 분해하고자 하는 객체를, 좌측엔 사응하는 객체 프로퍼티의 '패턴'을 넣습니다. 분해하려는 객체 프로퍼티의 키 목록을 패턴으로 사용하는 예시를 살펴봅시다.
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title, width, height} = options;
console.log(title); //Menu
console.log(width); // 100
console.log(height); // 200
프로퍼티 options.title과 options.width, options.height 에 저장된 값이 상응하는 변수에 할당된 것을 확인할 수 있습니다.
참고로 순서는 중요하지 않습니다. 아래와 같이 작성해도 위 예시와 동일하게 동작합니다.
let {height, width, title} = { title: "Menu", height: 200, width: 100 }
console.log(height); //200
console.log(width); //100
console.log(title); //Menu
할당 연산자 좌측엔 좀 더 복잡한 패턴이 올 수도 있습니다. 분해하려는 객체의 프로퍼티와 변수의 연결을 원하는 대로 조정할 수도 있습니다.
객체 프로퍼티를 프로퍼티 키와 다른 이름을 가진 변수에 저장해봅시다. option.width 를 w라는 변수에 저장하는 식으로 말이죠.
좌측 패턴에 콜론(:)을 사용하면 원하는 목표를 달성할 수 있습니다.
let option = {
title: "Menu",
width: 100,
height: 200
}
// { 객체 프로퍼티: 목표 변수}
let {width: w, height: h, title} = options;
//width -> w
//height -> h
//title -> title
console.log(title); //Menu
console.log(w); //100
console.log(h); //200
콜론은 '분해하려는 객체의 프로퍼티: 목표 변수' 와 같은 형태로 사용합니다. 위 예시에선 프로퍼티 width를 변수 w에, 프로퍼티 height를 변수 h 에 저장했습니다. 프로퍼티 title은 동일한 이름을 가진 변수 title에 저장됩니다.
프로퍼티가 없는 경우를 대비하여 =을 사용해 기본값을 설정하는 것도 가능합니다.
let options = {
title: "Menu"
};
let {width = 100, height = 200, title} = options;
console.log(title); // Menu
console.log(width); // 100
console.log(height); // 200
참조
코어 자바스크립트(정재남)
'TIL' 카테고리의 다른 글
가우스 계산법 (0) | 2023.02.16 |
---|---|
프로그래밍 기초 02(배열과 메서드) (1) | 2023.02.15 |
프로그래밍 기초01(항해99) (0) | 2023.02.14 |
동적 Element 생성시 함수인자 따옴표 (0) | 2023.02.09 |
Git push 오류 (Updates were rejected because ..) (0) | 2023.02.08 |