
자바스크립트의 스프레드 문법(spread syntax)은 배열, 객체 등의 요소를 확장하거나 복사할 때 사용하는 문법이다. 이는 배열과 객체 작업을 더 직관적이고 간단하게 만들어주는 유용한 기능이므로 이번 포스팅에서 정리하고 넘어가보자.
...은 하나로 뭉쳐 있는 여러 값들의 집합을 펼쳐서(전개, 분산하여, spread) 개별적인 값들의 목록으로 만든다.for...of문으로 순회할 수 있는 이터러블에 한정된다.const list = [1, 2, 3];
const arr1 = ...list // Syntax Error: Unexpected token ...
const arr2 = [...list]; // arr1의 모든 요소를 복사하여 arr2 생성
console.log(arr2); // [1, 2, 3]
const arr = [1, 2].concat([3, 4]);
console.log(arr); // [1, 2, 3, 4]
const arr = [ ...[1, 2], ...[3, 4] ];
console.log(arr); // [1, 2, 3, 4]
const arr1 = [1, 4];
const arr2 = [2, 3];
Array.prototype.splice.apply(arr1, [1, 0].concat(arr2));
console.log(arr1); // [1, 2, 3, 4]
const arr1 = [1, 4];
const arr2 = [2, 3];
arr1.splice(1, 0, ...arr2);
console.log(arr1); // [1, 2, 3, 4]
const origin = [1, 2];
const copy = origin.slice();
console.log(copy); [1, 2]
console.log(copy === origin); // false
const origin = [1, 2];
const copy = [...origin];
console.log(copy); [1, 2]
console.log(copy === origin); // false
function add(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(add(...numbers)); // 6
add(...numbers)는 add(1, 2, 3)과 동일하게 동작한다.const obj1 = { name: 'Sean', age: 25 };
const obj2 = { ...obj1 };
console.log(obj2); // { name: 'Sean', age: 25 }
const obj1 = { name: 'Sean', age: 25 };
const obj2 = { age: 30, city: 'New York' };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { name: 'Sean', age: 30, city: 'New York' }
obj2의 age 프로퍼티가 obj1의 age 프로퍼티를 덮어쓰고, city 프로퍼티가 추가됨structuredClone이나 Lodash 라이브러리의 _.cloneDeep 같은 깊은 복사 함수를 사용해야 한다.const nestedArr = [[1], [2], [3]];
const shallowCopy = [...nestedArr];
shallowCopy[0][0] = 100;
console.log(nestedArr); // [[100], [2], [3]]
shallowCopy를 수정했는데도 nestedArr이 함께 변경된다.