구조화 된 배열 또는 객체를 개별적인 변수에 할당하는 방법
배열의 인덱스를 기준으로 각 요소를 배열에서 가져와서 변수에 할당한다.
const array = [1, 2, 3, 4];
const [, two, three, four] = array; // array의 index 번호 순으로 각 변수에 array의 요소가 할당된다.
console.log(two); // 2
console.log(three); // 3
console.log(four); // 4
객체의 key를 사용하여 값을 변수에 할당한다.
const obj = {
name: 'junseo',
age: 25
};
const {name, age} = obj;
console.log(name); // junseo
console.log(age); // 25
const posts = [
{
"title": "notice",
"content": "Welcome!"
},
{
"title": "ask",
"content": "hello world"
}
];
나눠서 가져오는 방법
const [,ask] = posts;
const {title, content} = ask;
console.log(title); // "ask"
console.log(content); // "hello world"
한번에 가져오는 방법
const [,{title, content}] = posts;
console.log(title); // "ask"
console.log(content); // "hello world"
함수의 파라미터를 사용해서도 Destructuring 할 수 있다. 이를 이용해 click 이벤트가 발생할 때 event를 넘기는 것이 아니라 event.target 등 필요한 부분만 넘겨줄 수 있다.
const posts = [
{
"title": "notice",
"content": "Welcome!"
},
{
"title": "ask",
"content": "hello world"
}
];
function getAsk([,{content}]) {
console.log(content); // "hello world"
}
getAsk(posts);
event객체 내부의 target만 넘기는 방법
document.querySelector("div").addEventListener("click", function({target}){
console.log(target.innerText);
});