Elice SW engineer - TIL day 13

Circlewee·2022년 4월 20일
0

Elice SW 2 TIL

목록 보기
11/31

🍑 Spread, rest연산자(...)

const basicCookie = {
	base: 'cookie',
	madeIn: 'Korea',
}
const strawberryCookie = {
	...basicCookie,
	toping1: 'strawberry',
}
const chocoStrawberryCookie = {
	...strawberryCookie,
	toping2: 'chocolate',
}

console.log(basicCookie, strawberryCookie, chocoStrawberryCookie);
/* { base: 'cookie', madeIn: 'Korea' }
{ base: 'cookie', madeIn: 'Korea', toping1: 'strawberry' }
{ base: 'cookie', madeIn: 'Korea', toping1: 'strawberry', toping2: 'chocolate' }*/
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [...arr1, ...arr2, 5]; // spread
const [num, ...arr4] = arr3; // rest

console.log(arr3); // [1, 2, 3, 4, 5]
console.log(num, arr4); // 1 [2, 3, 4, 5]
  • 나머지를 그대로 담는 다고 해서 rest연산자이다. spread와 생김새는 같지만 용도는 다르다.
  • 이미 배열인 객체를 ...arr로 할당하면 배열을 풀어서 저장한다.
const arr = [1, 2, 3, 4, 5];
const arr2 = [6];
const [...arr3] = [...arr, ...arr2]; // rest, spread

console.log(arr3, ...arr3); // [1,2,3,4,5,6] 1 2 3 4 5 6

⭐ [...arr, ...arr2]는 이미 배열앞에 ...을 붙였기 때문에 [1, 2, 3, 4, 5, 6]이 된다. spread연산이다.
⭐ 배열에 저장할때는 ...을 붙이면 rest연산이므로 오른쪽 배열이 그대로 arr3이라는 변수에 새로운 배열로 담긴다.

profile
공부할 게 너무 많아요

0개의 댓글