알고리즘 눈덩이 2트 ⛄️⛄️
구조분해할당은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 Javascript표현식이다.
// 이름과 성을 요소로 가진 배열
let arr = ["Notorious", "Hong"]
// 구조 분해 할당을 이용해
// firstName엔 arr[0]을
// surname엔 arr[1]을 할당하였습니다.
let [firstName, surname] = arr;
alert(firstName); // Notorious
alert(surname); // Hong
이렇게 구조분해 할당을 통해 코드를 작성하면 배열의 요소를 직접 변수에 할당하는 것보다 코드 양이 줄어든다.
// 두 번째 요소는 필요하지 않음
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul
쉼표를 사용하면 필요하지 않은 배열 요소를 버릴 수 있다.
// 두 번째 요소는 필요하지 않음
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);
// 두 번째 요소는 필요하지 않음
let user = {};
[user.name, user.surname] = "Notorious Hong".split(' ');
alert(user.name); // Notorious
let guest = "Peter";
let admin = "Hastings";
// 변수 guest엔 Hastings, 변수 admin엔 Peter 저장되도록 값을 교환함
[guest, admin] = [admin, guest];
alert(`${guest} ${admin}`); // Hastings Peter(값 교환이 성공적으로 이뤄졌습니다!)
// 두 번째 요소는 필요하지 않음
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
배열 앞쪽에 위치한 값 몇 개만 필요하고 그 뒤의 나머지는 한 곳에 모아서 저장하고 싶을 때가 존재한다.
그럴떄 ...
를 붙이면 뒤의 나머지 요소를 가져올 수 있다.
let [firstName, surname] = [];
alert(firstName); // undefined
alert(surname); // undefined
할당하고자하는 변수의 갯수가 분해하고자 하는 배열의 길이보다 크더라도 에러가 발생하지 않는다.
할당할 값이 없으면 undefined로 취급되기 때문이다.
// 기본값
let [name = "Guest", surname = "Anonymous"] = ["Julius"];
alert(name); // Julius (배열에서 받아온 값)
alert(surname); // Anonymous (기본값)
하지만 =
를 이용하면 할당할 값이 없을 때 기본값으로 할당해줄 값을 미리 설정할 수 있다.
이러한 기본값들은 함수가 될 수도 있다.
기본값이 함수이고 할당할 값이 존재하지 않아 미리 설정해둔 기본값이 호출될 경우 함수가 호출된다.
let options = {
title: "Desk",
width: 100,
height: 200
};
let {title, width, height} = options;
alert(title); // Desk
alert(width); // 100
alert(height); // 200
할당 연산자 우측엔 분해되어진 값이 될 객체의 요소를 넣고, 좌측엔 분해 될 객체 그 자체를 넣는다.
프로퍼티 options.title
과 options.width
, options.height
에 저장된 값이 상응하는 변수에 할당된 것을 확인할 수 있다.
// let {...} 안의 순서가 바뀌어도 동일하게 동작함
let {height, width, title} = { title: "Desk", height: 200, width: 100 }
아래와 같이 작성해도 위 예시와 동일하게 동작한다.
콜론(:
)을 사용하면 된다.
let options = {
title: "Desk",
width: 100,
height: 200
};
// { 객체 프로퍼티: 목표 변수 }
let {width: w, height: h, title} = options;
// width -> w
// height -> h
// title -> title
alert(title); // Desk
alert(w); // 100
alert(h); // 200
=
를 사용하면 된다.
let options = {
title: "Desk"
};
let {width = 100, height = 200, title} = options;
alert(title); // Desk
alert(width); // 100
alert(height); // 200
options 객체의 key값에 width, height가 없었음에도 불구하고 기본값이 설정되어 값이 채워졌음을 알 수 있다.
물론 배열의 기본값 설정처럼 함수를 기본값으로 설정할 수 있다.
:
)과 기본값 설정(=
) 동시에 사용하기let options = {
title: "Desk"
};
let {width: w = 100, height: h = 200, title} = options;
alert(title); // Desk
alert(w); // 100
alert(h); // 200
let options = {
title: "Menu",
height: 200,
width: 100
};
// title = 이름이 title인 프로퍼티
// rest = 나머지 프로퍼티들
let {title, ...rest} = options;
// title엔 "Menu", rest엔 {height: 200, width: 100}이 할당됩니다.
alert(rest.height); // 200
alert(rest.width); // 100