티스토리 뷰

반응형

ES6의 Spread 연산자와 rest 파라미터에 대해 정리해보자.

 

 

 

 

Spread 연산자

이터러블(iterable) 객체를 개별 요소로 분리한다.

 

✏️ 이터러블 객체는 반복 가능한 객체를 일컫는다. Array, String, Map, Set, DOM 구조가 있다.

 

 

Object.createslice를 사용하지 않고도 배열이나 객체의 복사본을 쉽게 만들 수 있다.

 

console.log(...[1, 2, 3]); // 1, 2, 3
 
console.log(...'apple');  // a p p l e

 

function fruits(arr) {
  return [...arr, 'apple']
}

fruits(['grape', 'melon', 'lemon']); // ["grape", "melon", "lemon", "apple"]

 

function fruits(a, b, c) {
  console.log(a); // "grape"
  console.log(b); // "melon"
  console.log(c); // "lemon"
}

const arr = ['grape', 'melon', 'lemon'];
fruits(...arr);

 

 

Spread 연산자를 사용하면 깊은 복사(Deep copy)가 가능하다.

 

const arr1 = [1, 2, 3];
const arr2 = [...arr1]; // Spread 연산자로 arr1을 쪼갠다음 다시 대괄호로 감싸 배열로 만든 것

console.log(arr1 === arr2) // false

 

 

 

 

 

rest 파라미터

rest 파라미터는 함수의 파라미터 자리에 spread 연산자를 사용해 작성한 형태이다. spread와 반대로 생각하면 되는데, rest 파라미터는 파라미터로 오는 값들을 배열로 반환하기 때문이다.

 

function fruits(...rest) {
  console.log(rest); // ["grape", "melon", "lemon"]
}

fruits('grape', 'melon', 'lemon');

 

 

ES5의 arguments와 다른 점이 있다면, arguments는 유사 배열 객체이고 rest 파라미터는 배열이라는 것이다.

 

function fruits() {
  console.log(arguments); // {0: "grape", 1: "melon", 2: "lemon"}
}

fruits('grape', 'melon', 'lemon');

 

반응형
반응형
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31