28. Spread Syntax

다양한 데이터 구조를 공통된 반복 방식으로 순회할 수 있도록 해주는 프로토콜

Index


1. 스프레드 문법

  • 스프레드 문법(...)은 이터러블이나 객체의 요소를 개별 요소로 펼쳐서 복사하거나 전달할 때 사용된다. 배열, 객체, 함수 인자 등에서 간결하게 복제 · 병합 · 전달할 수 있는 문법이다.


1.1 함수 호출문의 인수목록에서 사용

// Rest 파라미터는 인수들의 목록을 배열로 전달받는다.

function foo(...rest) {
  console.log(rest); // 1, 2, 3 → [1, 2, 3]
}

// 스프레드 문법은 배열과 같은 이터러블을 펼쳐서 개별적인 값들의 목록을 만든다.
// [1, 2, 3] → 1, 2, 3



1.2 배열 리터럴 내부에서 사용하는 경우

1.2.1 concat의 역할을 대체

// 1) concat
let arr = [1, 2].concat[3, 4]
console.log(arr); // [1, 2, 3, 4]

// 2) spreadSyntax
const arr = [...[1, 2], ...[3, 4]]
console.log(arr); // [1, 2, 3, 4]


1.2.2 splice의 역할을 대체

// 1) splice
let arr1 = [1, 4];
let arr2 = [2, 3];
arr1.splice(1, 0, arr2);
console.log(arr1); // [1, [2, 3], 4]

// 2) spreadSyntax
const arr1 = [1, 4];
const arr2 = [2, 3];
arr1.splice(1, 0, ...arr2);
console.log(arr1); // [1, 2, 3, 4]


1.2.3 slice로 배열 복사

// 1) slice
let origin = [1, 2];
let copy = origin.slice();
console.log(copy); // [1, 2]
console.log(copy === origin); // false, 얕은복사

// 2) spreadSyntax
let origin = [1, 2];
let copy = [...origin];
console.log(copy); // [1, 2]
console.log(copy === origin) // false, 얕은복사


1.2.4 이터러블을 배열로 변환

// 1) slice
function sum() {
  let args = Array.prototype.slice.call(arguments);
  return args.reduce(function (pre, cur) {
    return pre + cur;
  }, 0);
}

console.log(sum(1, 2, 3)); // 6

// 2) spreadSyntax
function sum() {
  return [...arguments].reduce((pre, cur) => pre + cur, 0);
}

console.log(sum(1, 2, 3)); // 6



1.3 객체 리터럴 내부에서 사용하는 경우

// 1) 스프레드 프로퍼티
// 객체 복사(얕은 복사)
const obj = { x: 1, y: 2};
const copy = {...obj};
console.log(copy); // {x: 1, y: 2}
console.log(obj === copy); // false

// 객체 병합
const merged = {x: 1, y: 2, ...{a: 3, b: 4}};
console.log(merged); // {x: 1, y: 2, a: 3, b: 4}

// 객체 병합, 프로퍼티가 중복되는 경우 뒤에 위치한 프로퍼티가 우선권을 가짐
const merged = {...{x: 1, y: 2}, ...{y: 10, z: 3}};
console.log(merged); // {x: 1, y: 10, z: 3}




reference: 모던자바스크립트 Deep Dive 35장. Spread Syntax