javaScript(구조 분해 할당-Destructuring assignment)

Dev_Go·2022년 6월 27일
0

모던 자바스크립트

목록 보기
15/37
post-thumbnail

구조 분해 할당(비구조화 할당)-Destructuring assignment


구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.

예시

const user = {
  name: 'Winnie',
  age: 20,
  email: 'qwe3364@gmail.com'
}

const { name, age, email, address = 'Korea' } = user
// E.g, user.adress

console.log(`사용자의 이름은 ${name}입니다.`)
console.log(`${name}의 나이는 ${age}세입니다.`)
console.log(`${name}의 이메일 주소는 ${age}입니다.`)
console.log(address)

const fruits = ['Apple', 'Banana', 'Cherry']
const [, b, , d] = fruits
console.log(b, d)

결과

구문

const a, b, rest;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20


// Stage 4(finished) proposal
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}

설명

객체 및 배열 리터럴 표현식을 사용하면 즉석에서 쉽게 데이터 뭉치를 만들 수 있습니다.

const x = [1, 2, 3, 4, 5];

구조 분해 할당의 구문은 위와 비슷하지만, 대신 할당문의 좌변에서 사용하여, 원래 변수에서 어떤 값을 분해해 할당할지 정의합니다.

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

구조 분해 할당은 Perl이나 Python 등 다른 언어가 가지고 있는 기능입니다.

profile
프론트엔드 4년차

0개의 댓글