반응형
구조 분해 할당이란, 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 Js 표현식이다.
const array = [1,2,3,4,5]
const [a] = array;
console.log(a)
// 1
// 일부 요소만 가져오기
const [x, y, ...rest] = [1, 2, 3, 4, 5];
console.log(x); // 1
console.log(y); // 2
console.log(rest); // [3, 4, 5]
// 기본값 설정
const [p = 10, q = 20] = [1];
console.log(p); // 1
console.log(q); // 20
// 변수 교환
let m = 1, n = 2;
[m, n] = [n, m];
console.log(m); // 2
console.log(n); // 1
객체의 구조 분해 할당을 내가 설명해보자
const person = {
name : "alice",
height : 180,
weight : "90kg",
nation : "korean"
}
const {weight, nation} = person
console.log(weight);
console.log(nation);
//80kg korean
map reduce, filter 같은 배열 내장 메소드에서 구조 분해 할당이 쓰이는 경우는, 변수 칸에 변수가 아니라 배열이나 객체의 [], {} 형태를 직접적으로 넣어줌으로서 그 객체의 요소에다가 넣고자 하는 객체나 배열의 요소의 값을 바로 할당하는게 목적이다.
반응형