개발/알아둘 기본 개념
비구조화 할당
후누피
2023. 12. 23. 13:58
728x90
비구조화 할당이란 , 배열이나 객체의 속성을 해체하여 개별 변수에 값을 담을 수 있는 JS 표현식.
//배열의 비 구조화 할당(구조분해 할당) 적용 전
let arr = ["one", "two", "three"];
let one = arr[0];
let two = arr[1];
let three = arr[2];
//비 구조화 할당(구조분해 할당) 적용
let arr2 = ["one", "two", "three"];
let [one1, two2, three3] = arr2;
console.log(one1, two2, three3);
//배열선언 분리 비 구조화 할당
let [one11, two22, three33] = ["one", "two", "three"];
console.log(one11, two22, three33);
//스왑 전 코드가 길다.
let a = 10;
let b = 20;
let tmp = 0;
tmp = a;
a = b;
b = tmp;
console.log(a, b);
//스왑 사용
let c = 10;
let d = 20;
[c, d] = [d, c];
console.log("c와 d변경", c, d);
//객체의 비구조화 할당 전
let object = { one: "one", two: "two", three: "three" };
let o = object.one;
let t = object.two;
let thr = object.three;
console.log("o,t,thr :", o, t, thr);
//객체의 비구주화 할당
let object1 = { o1: "one", t2: "two", t3: "three" };
let { o1, t2, t3 } = object1;
console.log("o1,t2,t3:", o1, t2, t3);
//
let obj = { name: "김세훈", age: 32, hobby: "풋살" };
let { name: myName, age: myAge, hobby } = obj;
console.log(myName, myAge, hobby);
비구조화 할당을 통해 각 변수에 객체와 배열의 요소들을 담아서 출력 할 수 있었다.
또한, 객체나 배열의 정해진 key값을 변경할수있었다.
728x90