Javascript : 구조 분해 할당

kimsnmyng·2024년 12월 1일

Vanilla Javascript

목록 보기
12/23
// 1. 배열의 구조 분해 할당
let arr = [1, 2, 3];

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

let [one, two, three] = arr;
// 위와 같은 코드

console.log(one, two, three); // 1, 2, 3

let [one, two, three, four] = arr;
console.log(one, two, three, four) // 1, 2, 3, undefined

let [one, two, three, four = 4] = arr;
console.log(one, two, three, four) // 1, 2, 3, 4

//2. 객체의 구조 분해 할당

let person = {
  name: "김선명",
  age: 29,
  hobby: "잠자기"
}

let {name, age, hobby} = person // 객체는 중괄호로
console.log(name, age, hobby); // 김선명 29 잠자기

let {
  age: myAge, // 아 나는 age 값을 myAge에 할당하고 싶다.
  hobby,
  name,
  extra = "hello",
} = person;

console.log(name, myAge, hobby, extra); // 김선명 29 잠자기 hello

//3. 객체의 구조 분해 하당을 이용해서 함수의 매개변수를 받는 방법

const func = ({name, age, hobby, extra}) => {
  console.log(name, age, hobby, extra);
}

func(person); // 김선명 29 잠자기 undefined
profile
안녕하세요 김선명입니다.

0개의 댓글