[JS] 전개 구문(Spread syntax) ‘…’

전개 구문(Spread syntax) ‘…’ (dot dot dot)에 대해서

image

✍️ 전개 구문(Spread syntax)

자바스크립트에서 ... (dot dot dot)은 전개 구문(Spread syntax)라고 한다.

배열 표현과 같이 iterable, string to be expanded in places where zero or more arguments (for function calls), 요소(배열 리터럴 같은), 0개 또는 그 이상의 key-value쌍인 객체 표현(?) 에 사용가능하다. (출처: MDN)

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// output: 6

console.log(sum.apply(null, numbers));
// output: 6

배열 이어붙이기

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arrWrap = [...arr1, ...arr2];

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

기존 배열에 값을 추가하기

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// arr1.push(arr2); // [1, 2, 3, [4, 5, 6]] // arr2 배열 전체가 들어가 2차원 배열이 되어버렸다.
// Array.prototype.push.apply(arr1, arr2); // [1, 2, 3, 4, 5, 6] // 원하는 결과이나 코드가 복잡하다. // push를 apply로 호출하는 것이고 this에는 arr1을, push의 인자로는 arr2안의 요소를 전달한다.

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

객체 이어붙이기

const obj1 = {
  a: "A",
  b: "B",
};
const obj2 = {
  c: "C",
  d: "D",
};
const newObj = { obj1, obj2 };
console.log(newObj); // (1)
// (1) 결과
// 객체 각각의 값이 아니라 객체 자체가 들어가 2차원 객체가 되었다.
{
  obj1: {
    a: 'A',
    b: 'B'
  },
  obj2: {
    c: 'C',
    d: 'D'
  }
}

const obj1 = {
  a: "A",
  b: "B",
};
const obj2 = {
  c: "C",
  d: "D",
};
const newObj = { ...obj1, ...obj2 };
console.log(newObj); // (2)
// (2) 결과
// 객체 자체가 아니라 객체 각각의 값이 할당된다.
{
    a: 'A',
    b: 'B',
    c: 'C',
    d: 'D'
}

기존 배열을 보존하기

const arr1 = [1, 2, 3];
const arr2 = arr1.reverse();

console.log(arr1); // [3, 2, 1]
console.log(arr2); // [3, 2, 1]
// 전개 연산자를 이용해 기존 배열이 보존되도록 작성
const arr1 = [1, 2, 3];
const arr2 = [...arr1].reverse();

console.log(arr1); // [1, 2, 3]
console.log(arr2); // [3, 2, 1]

References