JavaScript/study

[javascript] ES6 구조 분해 할당

아2 2023. 5. 22. 19:06

구조 분해 할당 (Destructuring Assignment)은 자바스크립트에서 배열이나 객체를 해체하여 개별 변수로 분할하는 기능!!
이를 통해 배열의 각 요소나 객체의 속성을 쉽게 추출하여 변수에 할당할 수 있다.


구조분해할당이 필요한 이유??

1. 변수할당이 쉬워짐, 복합적인 데이터 구조(객체,배열,튜플 등) 값을 추출 해 여러 변수에 할당하는 간편한 방법을 제공함.

2. 코드가 간결해지고 유연해짐. 필요한 값만 추출해 변수에 할당 할 수 있다.

 

-아래는 구조분해할당 없이 일반코드로 작성했을때의 예시

let a = 10;
let b = 20;
let temp;

// 임시 변수를 사용하여 a와 b의 값을 교환
temp = a;
a = b;
b = temp;

console.log(a); // 출력: 20
console.log(b); // 출력: 10

-아래는 구조분해할당 적용예시

let a = 10;
let b = 20;

// 임시 변수를 사용하지 않고 a와 b의 값을 교환
[a, b] = [b, a];

console.log(a); // 출력: 20
console.log(b); // 출력: 10

배열 분해 할당

const numbers = [1, 2, 3];
const [a, b, c] = numbers;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

객체 분해 할당

-객체의 속성을 { name, age }와 같이 분해하여 각각의 변수에 할당

const person = { name: 'John', age: 30 };

const { name, age } = person;
console.log(name); // 'John'
console.log(age); // 30


// 초기값 할당도 가능하다!!
let { name, age, birthday = "today" } = person;
console.log(birthday); // today

기본값 설정

-구조 분해 할당 시 변수에 기본값을 설정할 수 있다. 해당 속성이나 요소가 undefined일 경우 기본값이 할당

const person = { name: 'John' };
const { name, age = 30 } = person;

console.log(name); // 'John'
console.log(age); // 30

중첩된 구조 분해 할당

-배열이나 객체 내부에 중첩된 구조도 분해할 수 있다

const numbers = [1, 2, [3, 4]];
const [a, b, [c, d]] = numbers;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4
const person = { name: 'John', address: { city: 'New York', country: 'USA' } };
const { name, address: { city, country } } = person;

console.log(name); // 'John'
console.log(city); // 'New York'
console.log(country); // 'USA'

 

구조 분해 할당은 코드를 간결하고 가독성있게 만들어주며, 배열이나 객체에서 필요한 값만 추출하여 사용할 수 있다.