구조 분해 (Destructing)

Jelkov Ahn·2021년 8월 8일
0

JS/NODE (Spread/Rest)

목록 보기
2/2
post-thumbnail

분해 후 새 변수에 할당

  • 배열
const [a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a) // 10
console.log(b) // 20
console.log(...rest) // 30 40 50
console.log(rest)// [30, 40, 50]
// 질문: a, b, rest는 각각 어떤 값인가요?
  • 객체
const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
console.log(a) // 10
console.log(b) // 20
console.log(...rest) // TypeError: Found non-callable @@iterator
console.log(rest)/ {c: 30, d: 40}
// 질문: a, b, rest는 각각 어떤 값인가요?

  • 선언 없이 할당을 할 경우

구조 분해를 통해 변수의 선언과 분리하여 변수에 값을 할당할 수 있습니다.

var a, b;

({a, b} = {a: 1, b: 2});

할당 문을 둘러싼 ( .. )는 선언 없이 객체 리터럴(object literal) 비구조화 할당을 사용할 때 필요한 구문입니다.

{a, b} = {a:1, b:2}는 유효한 독립 구문이 아닙니다. 좌변의 {a, b}이 객체 리터럴이 아닌 블록으로 간주되기 때문입니다.

하지만, ({a, b} = {a:1, b:2})는 유효한데, var {a, b} = {a:1, b:2}와 같습니다.

( .. ) 표현식 앞에는 세미콜론이 있어야 합니다. 그렇지 않을 경우 이전 줄과 연결되어 함수를 실행하는데 이용될 수 있습니다.

출처: mdn

객체분해예제

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

출처 : 코드스테이츠

profile
끝까지 ... 가면 된다.

0개의 댓글