ES6 문법 중 하나인 Destructuring이란 무엇일까요? 영단어 의미로는 '파괴하다'지만, 프로그래밍에서 Destructuring은 내가 원하는 요소만 '추출하는 것'입니다.

w3schools에서는 샌드위치 비유로 다음과 같이 설명했습니다.

 

https://www.w3schools.com/react/react_es6_destructuring.asp

 

React ES6 Destructuring

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

To illustrate destructuring, we'll make a sandwich. Do you take everything out of the refrigerator to make your sandwich? No, you only take out the items you would like to use on your sandwich.

Destructuring is exactly the same. We may have an array or object that we are working with, but we only need some of the items contained in these.

Destructuring makes it easy to extract only what is needed.

 

샌드위치 만들 때 냉장고에 있는 물건 전부다 빼내지 않죠? 샌드위치 만드는 데 필요한 것들만 꺼낼거에요.

Destructuring도 이와 비슷합니다. 배열이나 객체 중 필요한 부분만 잘라낼 수 있습니다.


Destructuring Arrays


Destructuring : 구조화된 객체, 배열 따위 요소를 비구조화(Destructure)하여 변수에 할당하다.

 

 우리는 이번 시간에 배열의 Destructuring에 대해 중점적으로 알아보도록 하겠습니다. 먼저 2015년 ES6 전의 Destructuring 문법에 대해 간략히 알아보겠습니다.

 

 ▽ ES5 Destructuring Arrays

var arr = [a, b, c];

var one = arr[0];
var two = arr[1];
var three = arr[2];

console.log(one, two, three);
#결과

a b c

 

 이렇게 ES5 문법으로는 Array의 각 요소를 변수에 하나씩 할당해야 했습니다. 여간 귀찮은 일이 아니었죠.

그래서 ES6에는 다음과 같은 수학 공식을 문법에 추가했습니다.

 △ 수학 배열의 동치구조입니다. 수학과 미묘하게 다른 점이 하나 있다면, 추출&할당이 Array의 index 기준으로 진행된다는 것입다. 우측의 배열의 인덱스 기준으로 좌측 변수에 할당된다는 것입니다. (변수할당의 특성상 원래 그렇긴 하죠.)

 

 이 문법 하나만으로 ES5와 다르게 얼마나 빠르게 Destructuring이 가능한 지 다음에서 볼 수 있습니다.

 

▽ ES6 Destructuring Arrays

let one, two, three;
[one, two, three] = [a, b, c];

console.log(one, two, three);
#결과

a b c

 ▽ 이렇게도 쓸 수 있습니다.

let arr = [a, b, c];
let [one, two, three] = arr;

 ▽ 혹은 이렇게도!

let [one, two, three] = [a, b, c];

 

 

응용


let a, b, c;

[a, b, c] = [1, 2, 3];
console.log(a, b, c);	//결과 : 1 2 3

[a, b] = [1];
console.log(a, b);	//결과 : 1 Undefined

[a] = [1, 2];
console.log(a);		//결과 : 1

[a, , c] = [1, 2, 3];
console.log(a, c)		//결과 : 1 3
[a = 10000, b, c] = [1, 2, 3];
console.log(a, b, c)		//결과 : 1 2 3

[a, b, c = 3] = [1, 2];
console.log(a, b, c)		//결과 : 1 2 3

 △ 위에서 언급한 것과 같이 추출&할당이 Array의 index 기준으로 진행되기 때문에 우측 배열의 값이 우선적으로 변수에 할당됩니다.

[a, ...c] = [1, 2, 3, 4];
console.log(a, c)		//결과 1 [2, 3, 4]

△ ES6의 Spread 문법입니다. 해당 내용 참조 바랍니다.

https://hwon-da.tistory.com/15

 

#03. [JS] ES6 최신문법

객체 만들기 (key) //옛날 문법 let name = "hwonda"; let age = 29; let person ={name:name, age:age} //ES6 문법 let name = "hwonda"; let age = 29; let person ={name, age} : 자동으로 변수 이름 = key 값으로 변경해줍니다. 객체 분

hwon-da.tistory.com

 

+ Recent posts