구조 분해 할당(Destructuring Assignment)은 배열이나 객체의 속성을 해체하여 개별 변수에 담을 수 있게 하는 JavaScript의 강력한 표현식입니다.
1. 배열 구조 분해
1-1) 기본 할당
배열의 요소들을 순서대로 새로운 변수에 할당할 수 있습니다:
const colors = ["green", "blue", "purple"];
const [c1, c2, c3] = colors;
console.log(c1); // "green"
console.log(c2); // "blue"
console.log(c3); // "purple"
1-2) 선언 분리 할당
변수 선언과 할당을 분리하여 구조분해를 할 수 있습니다:
let a, b;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
만약, 변수를 추가하고 싶을 때는 할당할 배열 내에 들어갈 자리가 있어야 한다. 없는 경우 undefined이 출력된다.
let arr ['a','b','c'];
let [one, two, three, four='d'] = arr;
console.log(one,two,three,four); //a,b,c,d
2. 객체 구조 분해
2-1) 기본 할당
객체의 속성을 변수로 분해할 수 있습니다:
const user = {
id: 42,
isVerified: true
};
const { id, isVerified } = user;
console.log(id); // 42
console.log(isVerified); // true
2-2) 새로운 변수명 할당
객체의 속성을 다른 이름의 변수로 할당할 수 있습니다:
const o = { p: 42, q: true };
const { p: foo, q: bar } = o;
console.log(foo); // 42
console.log(bar); // true
반응형
'Programming > Javascript' 카테고리의 다른 글
[JS] 원시 타입(Primitive Type)과 객체 타입(Object Type)의 이해 및 활용 (0) | 2025.04.24 |
---|---|
[JS] Spread 연산자와 Rest 매개변수 정리 (0) | 2025.04.23 |
[JS] 옵셔널 체이닝(Optional Chaining) 이란? (0) | 2025.01.06 |
[JS] JavaScript의 Truthy와 Falsy: 조건부 평가의 핵심 이해하기 (1) | 2025.01.03 |
[JS]JavaScript 객체와 배열 완벽 가이드 (0) | 2025.01.03 |