
구조 분해라는 뜻으로 구조화된 배열, 객체의 속성을 Destructuring하여 개별적인 변수에 할당하는 것이다.
코드 1)
const arr= [1,2,3];
const [x,y,z,w=4] =arr; // 기본 값 지정 가능
console.log(x, y, z,w); // 1 2 3 4
코드 2)
const now =new Date();
const formmattedDate =now.toISOString().substring(0,10); // 2024-06-17
const [year, month ,day ] = formmattedDate.split('-');
console.log(year, month, day); // 2024 06 17
코드 1)
const obj ={
name: "khw",
age: 25
}
const {age,name, residence="sokcho"} = obj; // 기본값 지정 가능
console.log(name, age,residence); // khw 25 sokcho
코드 2) 고차함수 filter 사용
const todos =[
{content:'HTML',completed:true},
{content:'CSS',completed:true},
{content:'JS',completed:false},
]
// 배열의 각 요소를 돌면서 completed 프로퍼티만 추출
//return 값이 true인 배열의 요소만 추출해 새로운 배열 반환
const completedTodos =todos.filter(({completed})=> completed);
console.log(completedTodos);
코드 3) 할당 받을 객체의 내부 객체의 프로퍼티 값을 할당 받고 싶을 경우
const info = {
name: "khw",
body: {
height:180,
weight:80,
skin: "yellow",
}
}
// 전달받은 객체의 body 키 안의 height, weight 키값 할당
function showHeightAndWweight({name, body,body:{height,weight}}){
console.log(name);// khw
console.log(body); // { height: 180, weight: 80, skin: 'yellow' }
console.log(height,weight); // 180 80
}
showHeightAndWweight(info);