구조 분해 (Destructing)

jeong dain·2022년 9월 1일
0

분해 후 새 변수에 할당하는 방식

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

// a = 10;
// b = 20;
// rest = [30, 40, 50];
  • 객체
const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}

// a = 10;
// b = 20;
// rest = {c: 30, d:40};
  • 객체에서 구조 분해 할당을 사용하는 경우, 선언(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) // jdoe is John

Reference

profile
Web Frontend Developer #TypeScript #React #NextJS🤸‍♀️

0개의 댓글

관련 채용 정보