반응형
JavaScript의 구조 분해 할당은 배열이나 객체의 속성을 쉽게 추출해서 변수에 할당할 수 있는 문법이다. 이걸 사용하면 코드가 깔끔해지고, 반복적인 코드도 줄일 수 있다.
1. 배열 구조 분해 할당
배열의 요소를 변수에 간편하게 할당할 수 있다.
예제
const fruits = ['사과', '바나나', '체리'];
// 구조 분해 할당
const [firstFruit, secondFruit] = fruits;
console.log(firstFruit); // 출력: 사과
console.log(secondFruit); // 출력: 바나나
여기서 fruits 배열의 첫 번째와 두 번째 요소를 각각 firstFruit와 secondFruit에 할당한다. 이렇게 배열의 요소를 쉽게 뽑아낼 수 있다.
2. 기본값 설정
구조 분해 할당할 때 기본값도 설정할 수 있다.
예제
const colors = ['빨강', '파랑'];
// 기본값 설정
const [primaryColor, secondaryColor, thirdColor = '초록'] = colors;
console.log(primaryColor); // 출력: 빨강
console.log(secondaryColor); // 출력: 파랑
console.log(thirdColor); // 출력: 초록
여기서 thirdColor는 기본값 '초록'을 갖게 된다. 배열에 세 번째 요소가 없으니까 기본값이 할당되는 것이다.
3. 객체 구조 분해 할당
객체의 속성을 변수에 쉽게 할당할 수 있다.
예제
const person = {
name: '홍길동',
age: 30,
country: '한국'
};
// 구조 분해 할당
const { name, age } = person;
console.log(name); // 출력: 홍길동
console.log(age); // 출력: 30
위 예제에서 person 객체의 name과 age 속성을 변수에 할당한다. 이렇게 객체의 속성도 간편하게 뽑아낼 수 있다.
4. 변수 이름 변경
구조 분해 할당할 때 변수 이름을 바꿀 수도 있다.
예제
const user = {
userName: '김철수',
userAge: 25
};
// 변수 이름 변경
const { userName: name, userAge: age } = user;
console.log(name); // 출력: 김철수
console.log(age); // 출력: 25
여기서 userName을 name으로, userAge를 age로 바꿔서 할당한다.
5. 중첩 구조 분해 할당
중첩된 객체에서도 구조 분해 할당을 사용할 수 있다.
예제
const employee = {
id: 101,
details: {
name: '이영희',
position: '개발자'
}
};
// 중첩 구조 분해 할당
const { details: { name, position } } = employee;
console.log(name); // 출력: 이영희
console.log(position); // 출력: 개발자
여기서는 employee 객체의 중첩된 details에서 name과 position을 추출한다.
결론
JavaScript의 구조 분해 할당은 배열과 객체의 요소를 간편하게 가져올 수 있는 유용한 기능이다. 이걸 사용하면 코드가 더 깔끔해지고, 변수를 선언하는 것도 훨씬 쉬워진다.
반응형
'IT개발 > JS 관련' 카테고리의 다른 글
[GSAP] GSAP(GreenSock Animation Platform) 라이브러리(애니메이션 구현) (0) | 2025.02.26 |
---|---|
[React] React 프로젝트에 prettier & eslint 설치하기 (0) | 2025.02.18 |
[React] React 프로젝트 생성 후 최초 렌더링 과정 이해하기(Vite 설치) (0) | 2025.02.18 |
[vue] 특정 페이지에서만 특정 클래스 추가하기 (0) | 2025.02.10 |
[vue] Vue 3 프로젝트에서 public/assets와 src/assets 폴더의 차이점 (0) | 2025.02.10 |
댓글