[JS] 비 구조화 할당(구조 분해 할당)

n-u·2022년 6월 15일
0

TIL

목록 보기
5/24
post-thumbnail

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

배열, 객체에서 원하는 값을 쉽고 빠르게 구할 수 있는 방법

1. 배열의 비구조화 할당

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

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

console.log(one, two, three);

비구조화 할당을 이용해 단축

let [one, two, three] = arr;
//대괄호를 이용해서 배열의 요소를 할당 받는 방법 => 비 구조화 할당
//배열은 인덱스를 통해 할당 받는다. 순서대로..?
console.log(one, two, three);

여기서 더 단축

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

응용 - 스왑

//스왑
let a = 10;
let b = 20;
[a, b] = [b, a];
console.log(a, b);

2. 객체의 비구조화 할당

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);
let object = { one: "one", two: "two", three: "three", name: "nnnn" };

let { name, one, two, three } = object;
//객체의 비구조화 할당은 객체의 키값을 이용해 할당된다.
//즉 순서가 아니라 키값을 {}안에 넣어줘야만 프로퍼티 키가 가지고 있는 값을 할당 받을 수 있다.

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

따라서 변수명이 키값으로 강제되는 경우가 있다.

여기서 키값의 변수명이 아니라 다른 변수명을 지정해주고 싶다면?

let object = { one: "one", two: "two", three: "three", name: "nnnn" };
let { name: myName, one: ONE, two: TWo, three, abc = "four" } = object;
console.log(ONE, TWo, three, myName, abc); //one two three nnnn

즉 비구조화 할당할때 :을 이용해 다른 변수명을 지정해 주면 된다.

profile
기록하며 발전하는 삶

0개의 댓글