JS - 비구조화 할당

gimmicks_u·2022년 5월 21일
0
post-thumbnail

비구조화 할당(구조분해 할당)

let arr = ['one', 'two', 'three'];

let one = arr[0];
let two = arr[1];
let three = arr[2];

console.log(one, two, three);
one two three
let arr = ['one', 'two', 'three'];

let [one1, two1, three1] = arr;
console.log(one1, two1, three1);

// 배열읫 선언 분리 비구조화 할당 
let [one2, two2, three2] = ['one', 'two', 'three'];
console.log(one2, two2, three2);
one two three
one two three

배열의 요소들을 하나 하나의 변수들로 할당할 경우 위와 같이 작성할 수 있지만, 비구조화 할당을 사용하면 더욱 간편하게 변수를 만들 수 있다.

let [one, two, three, four] = ['one', 'two', 'three'];
console.log(one, two, three, four);
one two three undefined

배열의 요소보다 더 많은 변수를 할당받고 싶을 경우 마지막 변수에undefined가 할당된다.

let [one, two, three, four = 'four'] = ['one', 'two', 'three'];
console.log(one, two, three, four);
one two three four

변수의 기본값을 설정해줄 수 있다.

활용

스왑

let a = 10;
let b = 20;
let tmp = 0;

tmp = a;
a = b;
b = tmp;
console.log(a, b);
20 10

각각 변수의 값을 서로 바꾸기 위해서는 tmp변수를 만들어 보관했다가 옮기는 방식을 사용했다.

let a = 10;
let b = 20;

[a, b] = [b, a];
console.log(a, b);
20 10

비구조화 할당을 이용해 간단하게 스왑기능을 구현할수 있다.

객체 할당

let object = { one: 'one', two: 'two', three: 'three' };

let one = object.one;
let two = object.two;
let three = object.three;

console.log(one, two, three);
one two three

객체의 값을 변수에 할당하는 것 또한 비구조화 할당을 활용할 수 있다.

let object = { one: 'one', two: 'two', three: 'three', name: '홍길동' };

let { name, one, two, three } = object;

console.log(one, two, three, name);
one two three 홍길동

객체의 비구조화 할당은 인덱스나 순서가 아닌 키 값을 기준으로 할당받아햐 한다.

let object = { one: 'one', two: 'two', three: 'three', name: '홍길동' };

let { name: myName, one, two, three } = object;

console.log(one, two, three, myName);
one two three 홍길동

변수의 이름을 다르게 할당할 수도 있다.

profile
Done is better than perfect

0개의 댓글