[Javascript] 구조 분해 할당

한별·2024년 2월 15일

Javascript

목록 보기
12/25

객체나 배열을 변수로 분해할 수 있게 해주는 특별한 문법

  • '모든 이터러블(iterable, 반복 가능한 객체)'에 구조 분해 할당을 적용할 수 있습니다.

  • 할당 연산자 좌측엔 ‘할당할 수 있는(assignables)’ 것이라면 어떤 것이든 올 수 있습니다.


배열 분해

// 이름과 성을 요소로 가진 배열
let arr = ["Hanbyeol", "Lee"]

// 구조 분해 할당을 이용해
// firstName엔 arr[0]을
// surname엔 arr[1]을 할당하였습니다.
let [firstName, surname] = arr;

console.log(firstName); // Hanbyeol
console.log(surname);  // Lee

요소 무시

필요하지 않은 배열 요소를 버릴 수 있음

let [a, ,c] = ["a", "b", "c"];
console.log(a) // a
console.log(c) // c

'…'로 나머지 요소 가져오기

let [a, b, ...rest] = ["a", "b", "c", "d", "e"]
console.log(a) // a
console.log(b) // b
console.log(rest) // ['c', 'd', 'e']

문자열 분해

let [a, b, c] = "abc"; // ["a", "b", "c"]

split을 이용하여 배열로 바꿔 분해할 수도 있다.

let [firstName, surname] = "Hanbyeol Lee".split(' ');
console.log(firstName); // Hanbyeol
console.log(surname);  // Lee

객체 분해

let props = {
  message: "Hello",
  width: 100,
  height: 200
};

// props.message를 msg에 할당
let {message: msg, width, height} = props;

// console.log(message); // error : message is not defined
console.log(msg) // Hello
console.log(width);  // 100
console.log(height); // 200

이를 이용하면 배열의 속성인 length도 가져올 수 있다.

let arr = [1, 2, 3, 4, 5]
let { length } = arr
console.log(length) // 5

'…'로 나머지 요소 가져오기

let props = {
  message: "Hello",
  width: 100,
  height: 200
};

let {message, ...rest} = props
console.log(message) // 'Hello'
console.log(rest) // {width: 100, height: 200}

기본값

할당할 값이 없으면 에러가 나지 않고 undefined가 할당된다

let [firstName, surname] = [];

alert(firstName); // undefined
alert(surname); // undefined

할당할 값이 없을 때 기본으로 할당해 줄 값인 '기본값(default value)'을 설정할 수 있다.

let [name = "Guest", surname = "Anonymous"] = ["Hanbyeol"];

alert(name);    // Hanbyeol (배열에서 받아온 값)
alert(surname); // Anonymous (기본값)

React에서 나도 모르게 사용하고 있었구만...

참고 자료

구조 분해 할당 | JAVASCRIPT.INFO

profile
글 잘 쓰고 싶어요

0개의 댓글