Destructuring assignment

2023. 12. 10. 04:30Javascript

728x90
반응형

Javascript에 Destructuring assignment, 한국어로 역구조화라는 신기한 문법이 있다는 것을 알았다. (Perl, Python에도 있다고 한다)

 

ES6에 추가된 이 문법은 구조화된 배열 또는 객체를 Destructuring하여 개별변수에 할당하는 것이다.
필요한 값만 추출해서 사용할 때 유용하다.


1. ES6 이전에는...

아래의 코드는 각각 ES5, ES6를 기준으로 배열의 값을 각 변수에 할당하는 코드이다.
ES6 이후 매우 간결해진 것을 알 수 있다.

// ES5
var arr = [1, 2, 3];

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

console.log(one, two, three); // 1 2 3
// ES6
const arr = [1, 2, 3];

// 배열의 인덱스를 기준으로 배열로부터 요소를 추출하여 변수에 할당
const [one, two, three] = arr;

console.log(one, two, three); // 1 2 3

2. 배열 Destructuring

배열을 Destructuring 할 때와 객체를 Destructuring 할 때 값을 할당하는 기준이 다르다.

 

배열은 인덱스를 기준으로 값을 할당하고, 객체는 키값을 기준으로 값을 할당한다.
배열 Destructuring 예시를 살펴보자.

let x, y, z;

/*
기본
*/
[x, y] = [1, 2];
console.log(x, y); // 1 2

/*
undefined
*/
[x, y] = [1];
console.log(x, y); // 1 undefined

/*
3은 추출/할당하지 않는다.
*/
[x, y] = [1, 2, 3];
console.log(x, y); // 1 2

/*
건너뛰기
*/
[x, , z] = [1, 2, 3];
console.log(x, z); // 1 3

/*
기본값
*/
[x, y, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3

[x, y = 10, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3

/*
spread 문법
*/
[x, ...y] = [1, 2, 3];
console.log(x, y); // 1 [ 2, 3 ]

3. 객체 Destructuring

객체를 Destructuring 할 때는 키값을 기준으로 값을 할당한다.
정확한 키값을 명시하지 않으면 값은 할당되지 않는다.

let p, q;

/*
기본
*/
{ p, q } = { p: 42, q: true };

console.log(p, q); // 42 true

/*
새로운 이름으로 할당
*/

{ p: foo, q: bar } = { p: 42, q: true };
console.log(foo, bar); //42 true

/*
기본값
*/
{ p = 10, q = false, t = 'hello' } = { p: 42, q: true };

console.log(p, q, t) // 42 true 'hello'

/*
Nested
*/
const person = {
  name: 'Lee',
  address: {
    zipCode: '03068',
    city: 'Seoul'
  }
};

const { address: { city } } = person;
console.log(city); // 'Seoul'

참조

728x90
반응형