배열이나 객체를 더 우아하게 사용하는 방법 (원하는 값을 더 쉽고 빠르게 쏙쏙 뽑아내는 방법) -> 비 구조화 할당(구조 분해 할당)
let arr = ["one","two","three"]; // 문자열 3개를 가지고 있는 배열
let one = arr[0];
let two = arr[1];
let three = arr[2];
console.log(one,two,three); // one two three
그런데 각 변수 3개에 값을 인덱스로 할당하려니 arr이라는 변수를 계속 사용해야 하는 반복코드 존재
let arr = ["one","two","three"];
let [one, two, three] = arr; //비 구조화 할당
console.log(one,two,three); // one two three
대괄호를 이용해 배열의 값을 순서대로 할당받아 사용할 수 있는 방법 : 배열의 비 구조화 할당(배열의 기본변수 비 구조화 할당)
더 간단하게👇
let [one, two, three] = ["one","two","three"]; //배열의 선언 분리 비 구조화 할당
console.log(one,two,three); // one two three
오른쪽에 있는 배열에서 0번,1번,2번 인덱스 꺼내서 쓰기
배열의 비 구조화 할당은 순서대로 배열의 요소를 변수에 쉽게 할당할 수 있는 방법
만약 네번째 변수까지 할당받고 싶다면 할당되지 못해서 undefined가 할당됨
let [one, two, three,four] = ["one","two","three"]; //배열의 선언 분리 비 구조화 할당
console.log(one,two,three,four); // one two three undefined
undefined라는 값이 할당되면 안되는 상황에서 기본값을 설정 가능 -> 할당받지 못하는 상황에 변수에 기본값을 지정해줄 수 O
let [one, two, three,four = "four"] = ["one","two","three"]; //배열의 선언 분리 비 구조화 할당
console.log(one,two,three,four); // one two three four
배열의 비 구조화 할당을 이용하면 두 개의 변수 값을 서로 바꾸는 swap에 활용 가능
let a = 10;
let b = 20;
let tmp = 0; //임시변수
tmp = a;
a = b;
b = tmp;
console.log(a,b); // 20 10
let a = 10;
let b = 20;
[a,b] = [b,a]; //왼쪽 배열의 0번 인덱스에는 오른쪽 배열의 0번 인덱스인 b의 값이 할당되고, 1번 인덱스에는 오른쪽 배열의 1번 인덱스인 a의 값이 할당
console.log(a,b); // 20 10
이번에는 객체의 비 구조화 할당을 알아보자
let object = {one : "one", two : "two", three : "three"}; //3개의 프로퍼티를 갖는 객체
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"}; //3개의 프로퍼티를 갖는 객체
let {one,two,three} = object; //object의 키 값을 기준으로 one이라는 키를 갖는 프로퍼티의 value 값을 one변수에 저장...
console.log(one,two,three); // one two three
객체의 비 구조화 할당은 배열의 인덱스(순서)를 이용하는 게 아니라, 키 값을 기준으로 할당
let object = {one : "one", two : "two", three : "three", name : "영주"}; //3개의 프로퍼티를 갖는 객체
let {name,one,two,three} = object; //object의 키 값을 기준으로 one이라는 키를 갖는 프로퍼티의 value 값을 one변수에 저장...
//순서 상관 X
console.log(one,two,three,name); // one two three 영주
name이라는 프로퍼티의 value를 키 값으로 접근해서 비 구조화 할당을 하지만 다른변수의 이름을 사용하고 싶을 경우에는
let object = {one : "one", two : "two", three : "three", name : "영주"}; //3개의 프로퍼티를 갖는 객체
let {name:myName,one,two,three} = object;
//변수의 이름을 바꿔서 할당 가능
//name이라는 키 값을 기준으로 value를 myName이라는 변수에 할당
console.log(one,two,three,myName); // one two three 영주
객체 비 구조화 할당 또한 기본값 설정 가능
let object = {one : "one", two : "two", three : "three", name : "영주"}; //3개의 프로퍼티를 갖는 객체
let {name:myName,one,two,three,abc = "four"} = object;
//변수의 이름을 바꿔서 할당 가능
//name이라는 키 값을 기준으로 value를 myName이라는 변수에 할당
console.log(one,two,three,myName,abc); // one two three 영주 four