구조 분해(Destructing)

Stella·2021년 7월 12일
0

구조 분해(Destructing)


구조 분해 할당은 Spread 문법을 이용하여 값을 해체한 후, 개별 값을 변수에 새로 할당하는 과정을 말합니다.

분해 후 새 변수에 할당


배열

const [a, b, ...rest] = [10, 20, 30, 40, 50];

// 질문: a, b, rest는 각각 어떤 값인가요?

객체

const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
// 질문: a, b, rest는 각각 어떤 값인가요?
  • 객체에서 구조 분해 할당을 사용하는 경우, 선언(const, let, var)과 함께 사용하지 않으면 에러가 발생할 수 있습니다.

함수에서 객체 분해


function whois({displayName: displayName, fullName: {firstName: name}}){
  console.log(displayName + " is " + name);
}

let user = {
  id: 42,
  displayName: "jdoe",
  fullName: {
      firstName: "John",
      lastName: "Doe"
  }
};

whois(user) // 질문: 콘솔에서 어떻게 출력될까요?
profile
메모장 쓰면서 공부중

0개의 댓글