[JS] 비 구조화 할당

이재훈·2023년 6월 2일
0

javascript

목록 보기
6/13
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 [one, two, three] = arr;

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

이렇게 대괄호를 사용하여 자동으로 변수 one two three를 초기화 시켰습니다.
``js
let [one, two, three] = ["one", "two", "three"];

console.log(one, two, three);

이렇게 배열을 선언 자체에서 분리 한다고 해서 배열의 선언 분리 비 구조화 할당이라고 합니다.
```js
let [one, two, three, four] = ["one", "two", "three"];

console.log(one, two, three, four); // one two three undefined
undefined

해당 코드는 four에 값이 할당되지 않아 undefined이 들어가는 것을 확인할 수 있습니다. 만약 기본 값을 넣고 싶다면 아래와 같이 하면 됩니다.

let [one, two, three = "3", four = "four"] = ["one", "two", "three"];

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

three 는 값이 비구조화 할당에 의해서 three로 초기화가 되고 four은 기본값인 four로 초기화가 됩니다.

swap

비 구조화 할당을 사용하면 쉽게 swap을 구현할 수 있습니다.

let a = 10;
let b = 20;
[a, b] = [b, a];

console.log(a, b); // 20 10

객체 비구조화 할당

let obj = { one: "1", two: "2", three: "3" };

let one = obj.one;

let two = obj.two;

let three = obj.three;

console.log(one, two, three); // 1 2 3 

이 코드를 비구조화 할당으로 바꿔보도록 하겠습니다.

let obj1 = { one: "1", two: "2", three: "3" };
let { one, two, three } = obj1;

console.log(one, two, three); // 1 2 3 

키값을 기준으로 값이 닮기게 됩니다.
만약 다른 변수의 이름을 가지고 싶다면 아래와 같이 하면 됩니다.

let obj1 = { one: "1", two: "2", three: "3", name: "jay" };
let { name: myName, one, two, three } = obj1;

console.log(one, two, three, myName); // 1 2 3 jay 

기본값 설정도 다음과 같이 가능합니다.

let obj1 = { one: "1", two: "2", three: "3", name: "jay" };
let { name: myName, one, two, three, basic = "basic" } = obj1;

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

해당 게시글은 인프런 강의
"한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지(이정환)"
를 정리한 내용입니다. 쉽게 잘 설명해주시니 여러분도 강의를 듣는 것을 추천드립니다.

profile
부족함을 인정하고 노력하자

0개의 댓글