스프레드연산자

Seonhee Kim·2023년 7월 12일

study

목록 보기
10/18

전개 연산자(Spread Operator) 는 객체나 배열, 함수의 인자 등 나열형 자료를 연결하거나 추출하는 데 사용되는 문법으로, 배열이나 객체 또는 함수 인자의 표현식 내부에서 배열이나 객체, 변수명 앞에 ... 을 붙여 사용한다

용도

  1. 원하는 객체 뽑아쓰기
  2. object 합치기
  3. 배열에 값 추가 (push 대신)
  4. 깊은 복사 (객체,배열의 깊이가 1depth인 경우만, 2 depth 이상이면 shallow copy)
// 2. object 합치기

const beverage = {coffee: 'latte', allergie:'milk'}
const info = {price: 30, orgin:'korea'};
const union = {...beverage, ...info};
console.log(union);
// 결과 {coffee: 'latte', allergie:'milk',price: 30, orgin:'korea'}

// 여기서 객체에 key를 업데이트 하고 싶은 경우
const union = {...beverage, ...info, price: 50};
console.log(union);
// 결과 {coffee: 'latte', allergie:'milk',price: 50, orgin:'korea'}
// 기존의 값은 변하지 않으면서 price만 변경됨
// 3. 배열에 값 추가

// spread -> 새로운 배열을 만듦
const beverage = ["americano", "latte"];
beverage = [...bevergae, "tea"]
console.log(beverage)// (3) ["americano", "latte", "tea"]

// push -> 기존의 배열을 수정하는 것
const beverage = ["americano", "latte"];
beverage.push("tea");
console.log(beverage)// (3) ["americano", "latte", "tea"]
profile
안녕하세요 ~_~

0개의 댓글