Js-비구조화 할당

뿌야·2022년 10월 17일
0

자바스크립트

목록 보기
7/24

<배열의 비구조화 할당>

let arr = ["one", "two", "three"];
let one = arr[0];
let two = arr[1];
let three = arr[2];
console.log(one, two, three);

위와 같이 변수를 할당할 수도 있지만 코드 한줄로 위와 같은 기능을 구현할 수 있다.

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

console.log(one, two, three);

이와 같은 방법을 배열의 비구조화 할당이라 한다.

더 나아가 다음과 같이 배열의 선언과 변수 할당을 합칠 수도 있다.

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

위와 같은 방법을 배열을 선언 자체에서 분리한다고 해서 배열의 선언 분리 비구조화 할당이라고 부르기도 한다.

즉 배열의 비구조화 할당은 순서대로 배열을 변수에 쉽게 할당할 수 있는 방법이다.

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

만약 위와 같이 순서대로 할당을 받을 수 없는 경우라면,

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

위의 경우처럼, 기본값을 설정해줄 수도 있다. 안그러면 four에 대해서는 undefined가 반환된다.

비구조화 할당을 이용하여 변수의 값을 서로 쉽게 교체도 가능하다.

let a = 10;
let b = 20;

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

콘솔창에는 20, 10이 뜨게 된다.

<객체의 비구조화 할당>
마찬가지 방식으로 객체에서도 비구조화 할당을 이용할 수 있다.
비구조화 할당은 key값을 기준으로 이루어진다.

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

let{one, two, three} = object;
console.log(one, two, three);

만약 키값을 그대로 변수 이름으로 이용하는 것이 아니라 내 변수이름을 지정하고 싶다면 다음과 같이 작성하면 된다.

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

let{one, two, three: numberThree} = object;
console.log(one, two, numberThree);

three라는 키값을 기준으로 numberThree라는 변수이름을 사용하겠다! 라는 말이다.
또한 배열과 마찬가지로 기본값 설정은 다음과 같이 가능하다.

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

let{one, two, three: numberThree, four = "four"} = object;
console.log(one, two, numberThree);

0개의 댓글