ddorongg 2023. 4. 3. 00:37
let arr = ["one", "two", "three"];
let one = arr[0];
let two = arr[1];
let three = arr[2];

console.log(one, two, three);

결과

 

- arr을 계속 반복하여 호출해야 하는 비효율 발생

 

비구조화 할당을 이용하여 코드 수정

대괄호를 이용하여 배열의 값을 순서대로 할당받아 사용

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, four);

결과

 

배열의 기본값을 설정하면 할당받지 못하는 상황에 변수에 기본값을 지정할 수 있음

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

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

 


비구조화 할당 사용시 두개의 변수 값을 바꾸는 스왑 사용 가능

let a = 10;

let b = 20;

let tmp = 0;

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

 

결과 

 

코드 수정

let a = 10;
let b = 20;

[a, b] = [b, a]

console.log(a, b);

 

결과


객체의 비구조화 할당

원래는 점표기법이나 괄호표기법 사용

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"};

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

결과

 

객체의 비구조화 할당은 인덱스를 이용하는 것이 아니라(순서x) 키값을 기준으로 할당함

let object = {one: "one", two: "two", three: "three", name:"서강준"};

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

결과

 


변수명이 키값으로 강제되는 현상 - 극복할 수 있는 방법 있음

let object = {one: "one", two: "two", three: "three", name:"서강준"};

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

name: boyName

name 을 boyName이라는 변수에 할당하겠다 라는 의미

 

결과