javaScript/js.Destructuring

디스트럭처링 할당(Destructuring assignment, 구조 분해 할당)

디스트럭처링 할당은 구조화된 배열 또는 객체를 destructuring하여 1개 이상의 변수에 개별적으로 할당하는 것
배열, 객체 리터럴에서 필요한 값만을 추출하여 변수에 할당할 때 유용하다.

1. 배열 디스트럭처링 할당

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 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;
// 배열 arr을 디스트럭처링하여 할당
// 할당 기준은 배열의 index
console.log(one, two, three); 1 2 3
//
//
// 할당을 위해서는 할당 연산자 왼쪽에 값을 할당 받을 변수를 선언(배열 리터럴)
let x, y;
[x, y] = [1, 2];
// const [x, y] = [1, 2]; 위 아래문은 동치
//
// 여러 개의 변수를 배열 형태로 선언하면 반드시 우변에 배열을 할당해야한다
const [x, y];
// SyntaxError: Missing initializer in destructuring declaration
//
// 변수에 기본값을 설정할 수 있다.
let x, y , z;

[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
  • 할당 연산자 왼쪽에 값을 할당 받을 변수를 선언해야 한다. (배열리터럴)

  • 할당의 기준은 배열의 인덱스이다.

  • 변수와 배열 요소의 개수가 반드시 일치할 필요는 없다.

  • 변수에 기본값을 설정할 수 있다.

  • Rest 파라미터와 유사하게 Rest 요소를 사용할 수 있다.

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

2. 객체 디스트럭처링 할당

ES5, 프로퍼티 키를 이용해서 프로퍼티를 디스트럭처링하여 변수에 할당

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// ES5
var user = { firstName: 'hoyoung'. lastName: 'jung' };

var firstName = user.firstName;
var lastName = user.lastName;

console.log(firstName, lastName); // hoyoung jung

//
// ES6
const user = { firstName: 'hoyoung'. lastName: 'jung' };
// 변수를 선언하고 객체 user를 디스트럭처링하여 할당
// 프로퍼티 키를 기준으로 디스트럭처링 할당이 이루어지고, 순서는 의미가 없다.
const { firstName, lastName } = user;

console.log(firstName, lastName); // hoyoung jung
//
// 다른 변수 이름으로 프로퍼티 값을 할당받기
const user = { firstName: 'hoyoung'. lastName: 'jung' };

const { lastName: lN, firstName: fN } = user;
console.log(fN, iN); // hoyoung jung

// 변수에 기본값 설정
const { firstName = 'hoyoung'. lastName } = { lastName: 'jung' };
console.log(firName, lastName); // hoyoung jung

const { firstName: fN = 'hoyoung', lastName: lN} = { lastName: 'jung'};
console.log(fN, lN); // hoyoung jung
  • 프로퍼티 키를 기준으로 디스트럭처링 할당이 이루어지고, 순서는 의미없다.

  • 다른 변수 이름으로 프로퍼티 값을 할당받을 수 있다.

  • 변수에 기본값을 설정할 수 있다.

  • 프로퍼티 키로 객체에서 필요한 프로퍼티 값만을 추출할 수 있다.

  • 객체를 인수로 전달받는 함수의 매개변수에도 사용할 수 있다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    const todo = { id: 1, content: 'HTML', completed: true };

    const { id } = todo;
    console.log(id); // 1

    function printTodo(todo) {
    console.log(`할일 ${todo.content}${todo.completed} ? '완료' : '바완료') 상태입니다.`);
    }
    printTodo({ id: 1, content: 'HTML', completed: true });
    // 할일 HTML은 완료 상태입니다.
    //
    //
    // 배열의 요소가 객체인 경우, 배열 디스트럭처링 할당과, 객체 디스트럭처링 할당 혼용 가능
    const todos = [
    { id: 1, content: 'HTML', completed: false },
    { id: 2, content: 'CSS', completed: false },
    { id: 3, content: 'javaScript', completed: true }
    ];
    const [, { id }] = todos;
    console.log; // 2
    //
    // 중첩 객체의 경우

    const user = {
    name: {
    lastName: 'jung',
    firstName: 'hoyoung'
    }
    };
    const { name: { lastName }} = user;
    console.log(lastName); // jung
  • Rest 파라미터와 유사하게 Rest 프로퍼티를 사용할 수 있다.

    1
    2
    const { x, ...rest } = { x: 1, y: 2, z: 3 };
    console.log(x, rest); // 1 { y: 2, z: 3 }
You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×