[JS]비 구조화 할당/ 구조분해

짱효·2023년 10월 28일

JS

목록 보기
13/21
let arr = ["one", "two", "three"];

let one = arr[0]; //계속 arr이 반복됨 줄여주고싶음!
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);

💁‍♀️마지막에 four로해서 할당받지 못하지만 할당받고싶어!!

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

console.log(one, two, three);

✔️기본값 설정!

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

console.log(one, two, three);

Swap에 유용

let a = 10;
let b = 20;

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

EX)

let object ={ one: "one", two : "two", three:"three", name : "jjang"}

let {name, one, two, three } = object;
console.log(one, two, three, name ) // one, twe, three, jjang
  • 키값을 기준으로 구조화 할당이 되어 상관없다.
  • 키값이 강제된다.

극복방법(다른 변수의 이름을 쓸수있다.)

  • 기본값 설정 가능
let object ={ one: "one", two : "two", three:"three", name : "jjang"}

let {name: myName, one : oneone, two, three, abc='four" } = object;
console.log(oneoneone, two, three, myName, abc ) // one, twe, three, jjang, four
profile
✨🌏확장해 나가는 프론트엔드 개발자입니다✏️

0개의 댓글