전개 구문과 구조분해할당

이서림·2024년 7월 30일

JavaScript

목록 보기
18/28

전개구문(Spread syntax)

  • 배열이나 객체와 같은 데이터 구조를 확장하기 위해 사용하는 문법
  • 기존 배열이나 객체를 복사해 완전히 새로운 값을 할당

배열의 전개구문

  • 대괄호 안에서 세 개의 점(...)을 사용하여 배열을 확장
    const fruits = ['사과', '파인애플', '수박'];
    const fish = ['조기', '갈치', '다금바리'];
    const food = [...fruits, ...fish];
    

    console.log(food);

객체의 전개구문

  • 중괄호 안에서 세 개의 점(...)을 사용하여 객체를 확장
    const weniv1 = {gary: 1, binky: 2};
    const weniv2 = {licat: 3};
    const weniv3 = {...weniv1, ...weniv2};
    

    console.log(weniv3);

  • 전개되는 객체들 중에 같은 이름의 key가 있다면, key 의 값은 나중에 온 객체의 키값으로 업데이트
    const me = { name: "wade", address: "jeju" };
    const newAddress = {address : "seoul"};
    const newMe = {...me, ...newAddress}
    

    console.log(newMe);

구조분해할당(destructuring)

  • 배열이나 객체와 같은 데이터 구조를 분해하여 변수에 할당하는 표현식
  • 간결성, 가독성, 변수 이름 변경, 기본값 설정

배열의 구조분해할당

let [a, b] = [1, 2];
console.log(a); // 출력: 1
console.log(b); // 출력: 2

객체의 구조분해할당

let { name, age } = { name: 'John', age: 30 };
console.log(name); // 출력: 'John'
console.log(age); // 출력: 30

함수의 구조분해할당

function foo([x, y]) {
  console.log(x); // 출력: 1
  console.log(y); // 출력: 2
}

foo([1, 2]);

profile
꾸준한 열정으로 나아가는 프론트엔드 개발자

0개의 댓글