Java Script

Growing_HJ·2024년 7월 1일

일기장

목록 보기
39/51

20240701 MON . 구조 분해 할당

구조 분해 할당: 배열이나 객체에서 요소를 해체하여 개별 변수에 그 값을 담는 것.

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

// 구조 분해 할당 방법
let [one2, two2, three2] = arr;
console.log(one2, two2, three2);

let arr2 = [1, 2, 3];
// 요소가 3개인데, 구조 분해 할당은 2개로 할 것임.
let [one3, two3] = arr2;

console.log(one3, two3);
arr2 = [1, 2];
let [one4, two4, three4] = arr2;
console.log(one4, two4, three4); //three4 = undefined 로 할당됨.
  1. 객체의 구조 분해 할당
console.log(" 객체 구조 분해 할당 ");
person = {
  name4: "용",
  age4: 26,
  location4: "Busan",
};
// 객체의 분해 할당의 기준은 객체의 key 를 기준으로 수행됨.
let { name4, age4, location4 } = person;
console.log(name4, age4, location4);

person = {
  name4: "용",
  age4: 26,
  location4: "Busan",
};

// 객체의 분해 할당이 객체의 key 를 기준으로 수행되지 않음. 따라서 모두 Undefined 값으로 할당됨.

객체 구조 분해 할당 vs 배열 구조 분해 할당

객체 구조 분해 할당

  • 객체에서 값을 꺼내온 뒤 할당하는 것을 의미.
    배열 구조 분해 할당과는 달리, 객체는 객체 내부 이름으로 꺼내온다는 차이가 있다.

배열 구조 분해 할당

  • 배열 구조 분해 할당에는 기본값을 선언할 수 있음.
    만약 배열의 길이가 짧거나 값이 없는 경우에는 (Undefined) 기본 값을 사용할 것.
    주의할 점은 반드시 Undefined 일 때만 기본값을 사용한다는 것!

0개의 댓글