구조분해할당(=비구조화할당)은 어떤 배열이나 객체를 분해해서 내부의 값들을 변수에 할당하는 문법입니다.
배열은 붙이고 싶은 이름에 순서대로 작성 해야 합니다.
//배열
function getClassmates (){
return ["영희", "철수"]
}
const [child1,child2] = getClassmates()
function getClassmates (name1, name2){
return [name2, name1]
}
getClassmates("훈이", "맹구")
객체는 이름을 key와 똑같이 해야하며 순서 중요하지 않습니다.
//객체
const child={
name: "영희",
age: 7,
school: "토끼초등학교"
}
const {age} = child
console.log(age) //7
function getChild(){
return {
name: "철수",
age: 13,
school: "다람쥐 초등학교"
}
}
getChild()
// {name: '철수', age: 13, school: '다람쥐 초등학교'}
const {school} = getChild()
console.log(school) //'다람쥐 초등학교'
구조분해 할당을 하면 객체나 배열을 변수로 사용할 수 있습니다.
function getWelcomeTemplate(name, age, school) {
const createdAt = 2020-02-10
return `
<html>
<body>
<h1>${name}님 가입을 환영합니다!!</h1>
<hr />
<div>이름 : ${name}</div>
<div>나이 : ${age}살</div>
<div>학교 : ${school}</div>
<div>가입일 : ${createdAt}</div>
</body>
</html>`
}
const myname = "철수"
const myage = 8
const myschool = "다람쥐 초등학교"
getWelcomeTemplate(myname, myage, myschool)
위의 코드와 같이 함수를 만들 경우, 매개변수를 하나 빼먹었을 경우 불안정한 함수가 된다.
function getWelcomeTemplate({name, age, school}) {
const createdAt = 2020-02-10
return `
<html>
<body>
<h1>${name}님 가입을 환영합니다!!</h1>
<hr />
<div>이름 : ${name}</div>
<div>나이 : ${age}살</div>
<div>학교 : ${school}</div>
<div>가입일 : ${createdAt}</div>
</body>
</html>`
}
const myuser = {
name: '철수',
age: 8,
school: "다람쥐초등학교"
}
getWelcomeTemplate(myuser)
위의 코드와 같이 구조분해할당을 하면 키와 변수가 동일하기 때문에 더 안정적인 함수가 된다.
※ key와 변수의 이름이 같아야한다.
const numbers = [5, undefined, null, 3, 1, 6, 0];
const [a, b = 4, c = 2, ...d] = numbers;
//[5,4,null,[3,1,6,0]]
console.log(a); //5
console.log(b); //4
console.log(c); //null
console.log(d[2]); //6
console.log(d[4]); //undefind
위의 코드와 같이 ...d는 rest 함수와 비슷하게 나머지요소들을 배열로 만들 수 있다 또 b=4 처럼 defalt 값을 줄 수 있다.
// 순서 바꾸기
const menu1 = "돈까스"
const menu2 = "김치찌개"
[menu1, menu2] = [menu2,menu2]
//이렇게 사용하면 값을 바꿀 수 있다.
객체 사용시에는
const myBestmusic = {
title: '빨간맛',
artist: '레드벨벳',
release: '2017.07.07.',
lyrics: '말 안해도 알아 ...'
};
const {title : songName, artist:singer, ...rest} = myBestSong
위 코드처럼 프로퍼티 이름을 바꿀 수 있다