본 게시물은 한빛미디어의 "모던 자바스크립트 핵심 가이드"(알베르토 몬탈레시 지음)를 공부하면서 작성되었습니다.

 

이전 글: [JS 핵심 가이드] 05. 문자열 메소드


 

06. 디스트럭처링(Destrcturing)

: 디스트럭처링 할당 문법배열의 값 또는 객체의 속성을 풀어서 별개의 변수로 쓸 수 있게 해주는 자바스크립트 표현식이다. (by, MDN정의)

 

6.1 객체 디스트럭처링

: 객체에서 변수를 생성할 때 

 

[ ES6 이전 ]

var person = {
	first: "Yasmine",
    last: "Kim",
};
var first = person.first;
var last = person.last;

 

[ ES6 이후 ]

const person = {
	first: "Yasmine",
    last: "Kim",
};

const {first, last} = person;

=> 디스트럭처링을 이용하여 person이 가진 속성에 접근함과 동시에 해당 속성 이름으로 변수 선언이 가능함을 알 수 있다.

 

[ 중첩된 사례 ]

const person = {
	first: "Yasmine",
    last: "Kim",
    links: {
    	social: {
        	facebook: "http://www.blablabla.com"
        }
        website: "http://websites.com"
    },
};

const {facebook} = person.links.social;
// 변수를 fb로 명명하고, 기본값을 다시 설정한다.
const {facebook: fb = "http://facebook.com"} = person.links.social;

 

 

6.2 배열 디스트럭처링

: 배열 디스트럭처링 [] ( cf, 객체 디스트럭처링 {} )

const person = ["Alberto", "Montalesi", 25]
const [name, surname, age] = person;

레스트 연산자(rest operator, ...)

const person = ["yangha", "kim", "pizza", "coconut water", "coffee"];

//레스트 연산자를 이용하여 나머지 값 전체를 얻는다.
const [name, surname, ...food] = person;
console.log(food) // ["pizza", "coconut water", "coffee"]

 

6.3 디스트럭처링을 이용하여 변수 교체하기

: 디스트럭처링을 이용해서 swap을 쉽게 할 수 있다.

let hungry = "yes";
let full = "no";

//swap
[hungry, full] = [full, hungry];
console.log(hungry, full) // no yes

 

 

 

 

공식문서(mdn): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

 

Destructuring assignment - JavaScript | MDN

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

developer.mozilla.org

 

+ Recent posts