객체나 배열을 변수로 분해할 수 있게 해주는 JS 문법!
let arr = ['Jane', 'Lee']
let [firstName, lastName] = arr;
console.log(firstName); // Jane
console.log(lastName); // Lee
let arr = [1, 2, 3, 4, 5]
let [one, two, ...rest] = arr;
console.log(rest); // [3, 4, 5]
...
로 가져올 수 있음let [a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7
// swap let apple = 1; let banana = 2; [apple, banana] = [banana, apple]; console.log(apple, banana); // 2 1
- 두 변수의 값 교환하기
*구조 분해 할당 없이 두 값을 교환하려면 임시 변수가 필요
let obj = { one: "one", two: "two", three: "three", name: "jane" t: true};
let { t, name, one, two, three } = obj;
console.log(one); // one
console.log(name); // jane
console.log(t); // true
key값이 아닌 다른 이름의 변수에 할당하고 싶을 때
let { name: myName } = obj; console.log(myName); // jane
기본값 설정과 새로운 변수 이름으로 할당을 같이 할 때
let { f: ff = false } = obj; console.log(ff); // false
중첩구조분해
let video = {
title: "cat",
intro: "please watch",
items: [1, 2]
};
function showThumnail({
title = untitled,
width = 200,
height = 100,
intro,
items: [item1, item2]
}) {
console.log(title, width, height); // width, height는 기본값
console.log(intro);
}
showThumnail(video);
// cat 200 100
// please watch
위와 같이 함수의 매개변수가 많거나 매개변수 기본값이 필요한 경우 유용