1-1 비구조화 할당

Jeon seong jin·2020년 1월 5일
1

JavaScript

목록 보기
6/11

비구조화 할당?

  • 배열이나 객체의 속성을 해체하여 그 값을 "개별 변수"에 담을 수 있게 하는 javaScript 표현식

  • 간단히 말해서 객체 혹은 배열 안의 값을 편하게 꺼내 쓸 수 있는 문법

Array

  • 기존에 배열을 사용할 때는 아래의 코드처럼 사용했습니다.
const animal = ['dog','cat','bird'];
const dog = animal[0]; //'dog'
const cat = animal[1]; // 'cat'
const bird = animal[2]; // 'bird'
  • animal이라는 'dog','cat','bird'를 가지고 있는 배열입니다. 이 변수가 가진 값을 각각 새로운 변수에 꺼내어 쓰려고 하면 위 코드처럼 index로 하나하나 지정을 해줘야 합니다. 그렇다면 항상 이렇게 찾아서 해야 될까요???

  • 이런 번거러움을 없애기 위해서는 비구조화 할당을 이용하면 됩니다. 아래의 코드를 볼까요?

[a,b,...c] = ['hello','half','one','two','three'];

console.log(a); //'hello'
console.log(b); // 'half'
console.log(c); // ['one','two','three'];
  • 비구조화 할당을 사용하니 코드가 훨씬 간결하고 보기 편합니다. 좌항의 각 요소에는 같은 index를 가지는 배열값이 할당됩니다. 또한 전개 연산자(...)을 사용하여 좌항에서 할당되지 않은 나머지 배열 값들을 사용할 수 있습니다.

  • var,let,const를 사용해 변수들의 범위를 선언할 수 있습니다.

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

전개 연산자 더 알아보기

const animal = ['cat','dog','bird']
const [cow,...rest] = animal
console.log(cow) // 'cat'
console.log(rest) // ['dog','bird']
const [a,b,c,d = '123'] = ['one','two','three'];
console.log(a) //'one'
console.log(b) //'two'
console.log(c) //'three'
console.log(d) // '123' 비구조화 할당을 할 때에는 "기본값" 지정이 가능하다!

비구조화 할당을 할 때 기본값 지정이 가능합니다.

let [a,b,...c,d] = ['a','b','c','d','e'];
console.log(a) 
console.log(c)
//a,c 모두 "SyntaxError: Rest element must be last element" 가 난다.
let [b,c,...d] = {a:1 ,b:2}
// 좌항과 우항이 다르니 에러가 발생!

전개 연산자 이후에 변수를 입력 하거나, 좌항과 우항이 다른 속성일 경우 에러가 발생합니다.

Object

let {a1,a2, ...rest_c} = {a1 : 10, a2 : 20,c:30, d: 40}
console.log(a1) //10
console.log(a2) //20
console.log(rest_c) //{c:30,d:40}

객체는 우항의 키 값이 좌항의 변수명과 매치됩니다.
배열과 같이 var,let,const가 적용 가능합니다.

원래의 key값과 다른 변수를 사용하는 방법은 아래와 같습니다.

const {cat,...animals} = {
	cat : 'CAT',
  	dog : 'DOG',
  	tiger : 'Tiger'
};
console.log(cat);//'CAT'
console.log(animals)//{dog:'DOG', tiger:'TIGER'}

배열에서의 비구조화 할당에 전개 연산자가 있듯이 객체의 비구조화 할당에도 나머지 패턴이 있습니다.

const {cat,dog,bird,lie = 'lie'} = {
	cat : 'cat',
  	dog : 'dog',
  	bird : 'bird',
}
console.log(lie) // ?? => 'lie'

배열에서의 비구조화 할당처럼 오브젝트에도 기본값을 지원합니다.

let {a : list, b : dumb, ...rest_c} = {a:10,b:20,c:30,d:40};
console.log(list)
console.log(dumb)

나머지 값을 뜻하는 전개 연산자는 우항의 키에 영향을 받지 않기 때문에 ...rest_c: "값" 와 같은 표현식은 의미가 없으며, 실제로 에러가 발생합니다.
우항의 키 값에 변수명으로 사용 불가능한 문자열이 있을 경우엔 아래와 같은 방식으로 비구조화 할 수 있습니다.

let key = 'key';
let {'animal' : animal_list, [key]:it_is_key} = {'animal' : 10, 'it is key' : 20};
console.log(animal) // 10
console.log(it_is_key)//20

Reference

profile
-기록일지

0개의 댓글