구조 분해 할당 (Destructuring assignment)

Park, Jinyong·2020년 4월 10일
0

Small, but Valuable.

목록 보기
11/19

Destructuring assignment - MDN Document

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

[a, b, ...rest] = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(a, b, rest); // 1 2 [3, 4, 5, 6, 7, 8, 9]

배열 구조 분해

순서대로 가져오고 남는 요소를 배열로 묶는다.

let [a, b, ...rest] = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(a, b, rest); // 1 2 [3, 4, 5, 6, 7, 8, 9]

값의 교환(swap)을 굉장히 쉽게 할 수 있다.

let a = 'a', b = 'b';

[a, b] = [b, a]
console.log(a, b); // 'b' 'a'

배열 반환을 더 간결히 수행할 수 있다.

function returnArray(...args) {
  return [...args];
}
let [a, b] = returnArray(3, 5, 7);
let [x, y, z] = returnArray(3, 5, 7);
console.log(a, b); // 3 5
console.log(x, y, z); // 3 5 7

객체 구조 분해

객체가 가지고 있는 key만 가져온다. 없으면 undefined를 가진다.

let {x, y} = {x: 'value1', y: 'value2'};
console.log(x, y); // value1 value2
let {y, z} = {x: 'value1', y: 'value2'};
console.log(y, z); // value2 undefined

선언과 분리하여 값을 할당할 때는 () 소괄호가 필요하다.

let x, y;
({x, y} = {x: 'value1', y: 'value2'});
console.log(x, y); // value1 value2

객체의 key 대신 새로운 변수의 이름을 할당할 수 있다.

let {x: foo, y: bar} = {x: 'value1', y: 'value2'};
console.log(foo, bar); // value1 value2

변수에 기본값을 할당할 수 있다. 할당으로 값은 덮어 쓰인다.

let {y: foo = 10, z: bar = 15} = {x: 'value1', y: 'value2'};
console.log(foo, bar); // value2 15

Spread properties를 지원한다.

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40, e: 50}
console.log(a, b, rest); // 10 20 {c: 30, d: 40, e: 50}

함수의 매개변수의 기본값 설정하기

function drawCircle({color = 'black', cords = {x: 0, y: 0}, radius = 5} = {}) {
  console.log(color, cords, radius);
  console.log('Drawing a circle...');
}
drawCircle(); // back { x: 0, y: 0 } 5
drawCircle({cords: {x: 10, y: 50}, radius: 50}); //  black { x: 10, y: 50 } 50
drawCircle({cords: {x: 10, y: 50}, radius: 50, color: 'red'}); // red { x: 10, y: 50 } 50

전체 매개변수는 {} 빈 객체로 default 설정되어 있기 때문에 어떠한 인자 전달 없이 동작한다. default값이 없다면 적어도 하나 이상의 인자를 제공해야 한다.

for...of 반복문과 구조 분해 응용

let people = [
  {
    name: "Mike Smith",
    family: {
      mother: "Jane Smith",
      father: "Harry Smith",
      sister: "Samantha Smith"
    },
    age: 35
  },
  {
    name: "Tom Jones",
    family: {
      mother: "Norah Jones",
      father: "Richard Jones",
      brother: "Howard Jones"
    },
    age: 25
  }
];

for (const {name: n, family: {father: f}} of people) {
  console.log("Name: " + n + ", Father: " + f);
}

// output:
// Name: Mike Smith, Father: Harry Smith
// Name: Tom Jones, Father: Richard Jones

0개의 댓글