프로그래밍/JS

[JS] ... (Three Dots) Operator

소복 2019. 11. 20. 19:23

ES6에서 추가된 문법

1. Rest Operator

  • 객체 혹은 배열의 남은 값을 변수에 할당할 때
const obj = {a: 1, b:2, c:3, d:4, e:5};

const {a, b, ...restObj} = obj;

// a와 b를 제외한 나머지 값들이 restObj에 객체로 할당된다

 

2. Spread Operator

  • 객체 혹은 배열의 값을 합칠 때, 혹은 복사할 때
  • 모든 값들만 꺼내서 사용할 때
  • (단, 값은 one depth는 deep copy지만 two depth 이상부턴 swallow copy가 된다.)
const arr = [1,2,3];
 
const arrCopy = [...arr, ...arr]; // [1,2,3,1,2,3,]
 
// 객체의 값들을 parameter로 대응해서 넘길 때
function foo (num1, num2, num3, num4){
    console.log(num1, num2, num3, num4);
}
 
foo(...arrCopy);
 
// 1 2 3 1 이 출력된다
// 대응되는 파라미터의 개수 이후의 값은 무시된다