프론트엔드 공부/javscript

객체구조분해할당(destructing) 예시

maggieH 2021. 4. 28. 23:29

const person ={
  name : 'Domenic',
  age:21
};
let{name,age,gender='Unknwon'} = person;
//console.log(name);//Domenic
//console.log(gender); //Unknwon

//다음과 같은 방식으로 함수내 매개변수에 지정할 수 있다.
function printDetails({name,age}){
  console.log(`이름은 ${name}이고 나이는${age}이다`);
}
printDetails(person);
//"이름은 Domenic이고 나이는21이다"

구조분해할당: 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식

var a, b, rest;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20


// Stage 4(finished) proposal
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment