spread와 rest

woodstock·2023년 12월 10일
post-thumbnail

spread와 rest

spread

  • 객체나 배열에서 중복된 부분을 퍼트릴 때
  • 함수를 호출 할 때 인수로 전달할 값을 퍼트릴 때

예제 1.

const toy = {
  type: "bear",
  price: 15000,
};
const blueToy = {
  ...toy,
  color: "blue",
};

const yellowToy = {
  ...toy,
  color: "yellow",
};

console.log(blueToy); // { type: 'bear', price: 15000, color: 'blue' }
console.log(yellowToy); // { type: 'bear', price: 15000, color: 'yellow' }

예제 2.

const color1 = ["red", "orange", "yellow"];
const color2 = ["blue", "navy", "purple"];
const rainbow = [...color1, 'green', ...color2];

console.log(rainbow); // [ 'red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple' ]

예제 3.

const print = (a, b, c, d, e, f) => {
  console.log(a, b, c, d, e, f);
};

const numbers = [1, 2, 3, 4, 5, 6];
print(...numbers); // 1 2 3 4 5 6

rest

  • 객체나 배열에서 특정 부분들을 하나의 객체나 배열로 묶어야 할 때
  • 구조분해 할당을 사용해 배열이나 객체의 값을 묶어서 할당할 때
  • 함수의 매개변수로 많은 값들을 전달받거나 특정 매개변수들을 제외한 나머지 매개변수들을 묶어서 사용할 때

예제 1.

const blueToy = {
  type: "bear",
  price: 15000,
  color: "blue",
};

// 구조분해할당을 통해 프로퍼티의 값을 변수들에 할당
const {type, price, color} = blueToy;

console.log(type); // bear
console.log(price); // 15000
console.log(color); //blue
const {type, ...rest} = blueToy;

console.log(type); // bear
console.log(rest); // { price: 15000, color: 'blue' }

주의할 점

rest문법은 spread와는 다르게 순서에 상관없이 여러 번 작성할 수 없고 항상 맨 마지막에 작성해야 한다.

// TypeError
const {...rest, type} = blueToy; // ❌

예제 2.

const color = ["red", "orange", "yellow", "green"];
const [c1, c2, ...rest] = color;

console.log(c1, c2); // red orange
console.log(rest); // [ 'yellow', 'green' ]

예제 3.

const print = (a, b, ...rest) => {
  console.log(a, b, rest);
};

print(1, 2, 3, 4, 5, 6); // 1 2 [ 3, 4, 5, 6 ]

예제 4.

const print = (...rest) => {
  console.log(rest);
};

const numbers = [1, 2, 3, 4, 5, 6];
print(...numbers); // [ 1, 2, 3, 4, 5, 6 ]
profile
해내는 사람

0개의 댓글