[JavaScript] 배열과 객체의 단축 문법(구조 분해 할당)

Hailey Song·2020년 9월 1일
0

1. 배열의 단축 문법

1) 기본적인 구조 분해 할당

변수 a, b에 각각의 변수가 위치하는 arr 인덱스 값을 할당할 수 있다.

let arr = [1,2,3,4,5]
let [a, b] = arr;
console.log(a); // 1
console.log(b); // 2

2) 쉼표로 건너뛰기

쉼표로 필요없는 인덱스를 뛰어넘어 할당할 수 있다.

let arr = [1,2,3,4,5]
let [ , , c, d, e] = arr;
console.log(c); // 3
console.log(d); // 4
console.log(e); // 5

3) 나머지를 배열로 받아오기

spread operator을 통해 나머지 값을 배열로 받아올 수 있다.

let arr = [1,2,3,4,5]
let [a, ...rest] = arr // 굳이 'rest'로 쓰지 않아도 됨
console.log(a); // 1
console.log(rest); // [2, 3, 4, 5]

단, spread operator는 마지막 변수에 사용되어야 한다.

let arr = [1,2,3,4,5]
let [a, ...rest, c] = arr
// Uncaught SyntaxError: Rest element must be last element

4) iterable에도 적용 가능

let [a, b, c] = 'apple'
console.log(a); // 'a'
console.log(b); // 'p'
console.log(c); // 'p'

let [a,b,c] = 'can'.split('')
console.log(a); // 'c'
console.log(b); // 'a'
console.log(c); // 'n'

5) default value 설정 가능

let [a, b, c = 'do'] = 'you can'.split(' ');
console.log(a); // 'you'
console.log(b); // 'can'
console.log(c); // 'do'

2. 객체의 단축 문법

1) 기본적인 구조 분해 할당

const cat = { name: '야통', crying: '이얏호응!' };
const {name} = cat
const {crying} = cat
console.log(name) // '야통'
console.log(crying) // '이얏호응!'
// 야통이 울음소리 내 핸드폰 알람소리인 건 안 비밀..

2) spread operator로 나머지 객체 받아오기

const cat = { name: '야통', crying: '이얏호응!' };
const { name, ...args } = cat;
console.log(args) // {crying: "이얏호응!"}

3) 객체 덮어쓰기

const cat = { name: '야통', crying: '이얏호응!', servant: 'haha ha'}
const anotherCat = {
  ...cat,
  name: '연님',
  crying: '야옹'
}
console.log(anotherCat) // { name: '연님', crying: '야옹', servant: 'haha ha'}

순서에 따라 덮어 씌우는 값이 바뀔 수 있다.

const cat = { name: '야통', crying: '이얏호응!', servant: 'haha ha'}
const anotherCat = {
  name: '연님',
  crying: '야옹',
  ...cat
}
console.log(anotherCat) // { name: '야통', crying: '이얏호응!', servant: 'haha ha'}

참고 자료

0개의 댓글