개발을 하다 보면 객체나 배열을 전달해야하는 경우가 생긴다. 하지만, 객체나 배열에 저장된 데이터 전체가 아닌 일부만 필요한 경우도 많다. 이럴 때 객체나 배열을 변수로 분해할 수 있게 해주는 문법이 구조 분해 할당(destructuring assignment)
이다.
배열 분해하기
기본 문법
let arr = ['Kevin', 'Kim]
// 구조 분해 할당
let [firstName, lastName] = arr;
console.log(firstName); // 'Kevin'
console.log(lastName); // 'Kim'
쉼표로 요소 무시하기
// 두 번째 요소는 필요하지 않음
let [firstName, , title] = ['Julius', 'Caesar', 'Consul']
console.log(title); // 'Consul'
할당 연산자 우측엔 모든 이터러블이 올 수 있다.
let [a, b, c] = 'abc'; // ['a', 'b', 'c']
let [one, two, three] = new Set([1, 2, 3]);
'...'로 나머지 요소를 할당
let [name1, name2, ...rest] = ['Julius', 'Caesar', 'Consul', 'of the Roman Republic'];
console.log(name1); // 'Julius'
console.log(name2); // 'Caesar'
// `rest`는 배열
console.log(rest); // ['Consul', 'of the Roman Republic']
console.log(rest[0]); // 'Consul'
console.log(rest[1]); // 'of the Roman Republic'
console.log(rest.length); // 2
객체 분해하기
기본 문법
let options = {
title: 'Menu',
width: 100,
height: 200
};
// 객체 구조할당은 순서가 바뀌어도 상응하는 변수에 할당된다.
let {height, width, title} = options;
console.log(title); // 'Menu'
console.log(width); // 100
console.log(height); // 200
객체 프로퍼티를 프로퍼티 키와 다른 이름을 가진 변수에 저장할 수 있다
let options = {
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
기본 값 설정
// 프로퍼티가 없는 경우를 대비
let {width = 100, height = 200, title} = options;
원하는 데이터만 뽑아오기
let options = {
title: `Menu`,
width: 100,
height: 200
};
// title만 변수로 뽑아내기
let { title } = options;
console.log(title); // `Menu`
'...'로 나머지 요소 할당
let options = {
title: `Menu`,
height: 200,
width: 100
};
// title = 이름이 title인 프로퍼티
// rest = 나머지 프로퍼티들
let {title, ...rest} = options;
console.log(title); // `Menu`
console.log(rest); // {height: 200, width: 100}
'프로그래밍 공부 > Javascript' 카테고리의 다른 글
submit 이벤트와 preventDefault (0) | 2021.10.03 |
---|---|
HTMLCollection 과 NodeList (0) | 2021.10.03 |
더 좋은 퍼포먼스를 위한 createDocumentFragment (0) | 2021.10.02 |
고차함수 / TIL 17일차 (0) | 2021.09.14 |
DOM / TIL 15~16일차 (0) | 2021.09.10 |