spread 문법 사용방법

HYUK·2023년 1월 23일
0

javascript

목록 보기
4/4

1. spread 문법

spread 라는 단어가 가지고 있는 의미는 펼치다, 퍼뜨리다 이다. 이 문법을 사용하면, 객체 혹은 배열을 펼칠수있다. 아래 코드를 통해서 확인해 보도록 하겠다.

const car = {
  name: 'car1'
};

const cuteCar = {
  name: 'car1',
  attribute: 'cute'
};

const whiteCuteCar = {
  name: 'car1',
  attribute: 'cute',
  color: 'white'
};

console.log(car); // {name : car1}
console.log(cuteCar); // {name : car1, attribute : cute}
console.log(whiteCuteCar); // {name:car1, attribute: cute, color: white}

위 코드에서의 핵심은, 기존의 것을 건들이지 않고, 새로운 객체를 만든다는 것이다. 이러한 상황에 사용 할 수 있는 유용한 문법이 spread 이다.

위의 코드를 spread 문법을 사용하면 아래와 같이 작성 할 수 있다.

const car = {
  name: 'car1'
};

const cuteCar = {
  ...car,
  attribute: 'cute'
};

const whiteCuteCar = {
  ...cuteCar,
  color: 'white'
};

console.log(car);
console.log(cuteCar);
console.log(whiteCuteCar);

또한 이러한 객체 말고도 배열에서도 사용이 가능한데 아래 코드를 통해서 확인해보겠다.

const numbers = [1, 2, 3, 4, 5];

const spreadNumbers = [...numbers, 1000, ...numbers];
console.log(spreadNumbers); // [1, 2, 3, 4, 5, 1000, 1, 2, 3, 4, 5]
profile
step by step

0개의 댓글