Spread operator 기본 사용법

ES6 에서 추가된 Spread operator는 … 기호를 붙여서 배열이나 객체의 값을 펼쳐주는 연산자이다.
배열과 객체 이름 앞에 … 을 사용해주면, 배열에서 괄호를 제거해 내부의 값만 빼서 펼쳐준다.
데이터의 연결, 복사 등으로 유용하게 활용할 수 있다.
괄호를 제거해 주는 연산자 이므로 소괄호 / 중괄호 / 대괄호 내부에서만 사용할 수 있다.

1
2
3
4
5
6
const words = ["hello", "world"];
const number = { a: 1, b: 2, c: 3 };

console.log(words); // output: ['hello', 'world']
console.log(...words); // output: hello world
console.log(...number); // output: a: 1, b: 2, c: 3



배열 병합하기

기존에 두개의 배열을 Spread operator을 활용해 병합할 수 있다.

1
2
3
4
5
const num1 = ["1", "2", "3"];
const num2 = ["4", "5", "6"];

const sum = [...num1, ...num2];
console.log(sum); // output: [ 1, 2, 3, 4, 5, 6 ]



배열 복사하기

배열을 복사하는 경우 새로운 배열은 기존의 배열을 참조한다.

1
2
3
4
5
6
7
const friends1 = ["Jessie", "Tony"];
const friends2 = friends1;

friends1.push("Brian");

console.log(friends1); // output: ['Jessie','Tony', 'Brian']
console.log(friends2); // output: ['Jessie','Tony', 'Brian']

그런데 그냥 이렇게 배열을 복사하면 값의 공유가 일어나기 때문에,
friends1을 수정하면 friends2까지 같이 바뀌어버리는 문제가 생긴다.
따라서 값을 공유하지 않고 독립적인 값을 저장하도록 Spread operator을 사용한다.

1
2
3
4
5
6
7
const friends1 = ["Jessie", "Tony"];
const friends2 = [...friends1];

friends1.push("Brian");

console.log(friends1); // output: ['Jessie','Tony', 'Brian']
console.log(friends2); // output: ['Jessie','Tony']

friends1은 push 메소드로 인해 값이 추가되었지만,
이미 friends2는 friends1의 값만 빼서 저장해둔 상태이기때문에 변화한 값의 공유가 일어나지 않는다.



객체 복사, 업데이트 하기

1
2
3
4
const profile = { name: "Jessie", age: 20 };
const newProfile = { ...profile, height: 180 };

console.log(newProfile); // output: {name: 'Jessie', age: 20, height: 180}

위 코드와 같이 객체의 속성값을 복사해와서 추가해줄 수 있다.

1
2
3
4
const profile = { name: "Jessie", age: 20 };
const newProfile = { ...profile, height: 180, name: "Tony" };

console.log(newProfile); // output: {name: 'Tony', age: 20, height: 180}

속성값이 중복되는 경우, 더 뒤에있는 값으로 덮어쓰는 방식으로 처리되어 자료를 업데이트 할 수 있다.



함수의 파라미터로 활용하기

1
2
3
4
5
6
7
function calculator(a, b, c) {
  console.log(a + b + c);
}

const number = [10, 20, 30];

calculator(...number); // output: 60

배열 내의 자료를 함수의 파라미터로 활용하기 위해 각각의 데이터를 입력하지 않고,
Spread operator를 활용해 한번에 배열 데이터를 넣어줄 수 있다.

Leave a comment