Rest, Spread 연산자

2020. 4. 9. 09:08웹/Javascript(ES6+)

Spread 연산자

  • 이터러블 오브젝트(Iterable Object)의 엘리먼트를 하나씩 분기

  • 전개한 결과를 변수에 할당 / 호출하는 함수의 파라미터 인수 

 

 

예제) 기존 객체를 복사, 새로운 객체를 반환

// 새로운 객체 생성
const book = {
    action : 'read'
};

const js_book = {
    ...book,
    title: 'JS'
};

const react_book = {
    ...js_book,
    title: 'react',
    price: '1000'
};

console.log(book);
console.log(js_book);
console.log(react_book);


console.log('------------------------------------------------');

// 주소값 참조
const book2 = {
action: 'read'
};

const js_book2 = book2;
js_book2.title = 'JS';

const react_book2 = js_book2;
react_book2.title = 'react';
react_book2.price = '1000';

console.log(book2);
console.log(js_book2);
console.log(react_book2);

출력결과

 

 

예제) 배열에서의 spread

const animals = ['강아지', '고양이'];
const animals2 = [...animals, '토끼'];

// 동일 기능
const concat_animals = animals.concat('토끼');

console.log(animals);
console.log(animals2);
console.log(concat_animals);


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

console.log(numbers);
console.log(spread_arr);

출력결과

 

 

 

Rest 연산자(Rest Parameter)

  • 함수의 파라미터 정해지지 않은 수(부정수) 인수를 배열로 나타낼 때 사용

  • 함수의 마지막 파라미터에 '...' 붙여 모든 인수를 배열로 대체

 

 

예제) 

function customRestFunction(a, b, ...arr) {
    console.log(a);
    console.log(b);
    console.log(arr);
    console.log(arr instanceof Array);
}

// Array
customRestFunction(1, 'A', [1,2,3,4,5]);

// Array
customRestFunction(1, 'A', 1, 2, 3, 4, 5);

// Object
customRestFunction(1, 'A', {name : 'aa', age: 23});

 

출력결과

 

 

Rest와 Arguments 객체의 차이

  • Rest 파라미터의 경우 구분된 이름(함수의 인자로 정의된 것)이 주어지지 않은 대상

  • arguments 객체는 함수로 전달된 모든 인수를 포함

  • arugments 객체의 경우 배열이 아님 / Rest 파라미터의 경우 배열

 

 

 

 

 

 

출처

https://jaeyeophan.github.io/2017/04/18/ES6-4-Spread-Rest-parameter/

 

' > Javascript(ES6+)' 카테고리의 다른 글

비동기 처리 - Promise  (0) 2020.06.16
iterator 와 for-of  (0) 2020.04.10
Destructuring(구조 분해 할당)  (0) 2020.04.08
템플릿 리터럴 문자열 표현식  (0) 2020.04.08
화살표 함수(Arrow Function)  (0) 2020.04.07