ES 2015에서 새롭게 등장한 문법으로 배열에서 주로 유용하게 사용합니다. "펄치다"라는 단어의 뜻과 연관되어 하나로 묶인 값을 여러 개로 펼치는 개념입니다.
const array = ['Google','Naver'];
console.log(array); // ['Google', 'Naver']
console.log(...array); // Google Naver
코드 출력 결과와 같이 Spread를 사용하면 목록의 값이 출력되는 것을 알 수 있습니다. 일반적으로 배열을 복사하려고 하면 다음과 같이 기존의 값도 변경시키기 때문에 복사를 하려면 다른 방법을 사용해야 하는대요.
const array = ['Google','Naver'];
const array2 = array;
array2.push('Tistory'); // push는 array2에 했지만 array1에도 추가됨
console.log(array); // ['Google', 'Naver', 'Tistory']
console.log(array2); // ['Google', 'Naver', 'Tistory']
이런 문제를 해결하려면 배열의 slice 메서드를 이용할 수 있겠지만 Spread 구문을 사용해서 복사해도 같은 리턴값을 가지는 것을 볼 수 있습니다.
const array = ['Google','Naver'];
const array2 = array.slice();
array2.push('Tistory');
console.log(array); // ['Google', 'Naver']
console.log(array2); // ['Google', 'Naver', 'Tistory']
const array = ['Google','Naver'];
const array2 = [...array];
array2.push('Tistory');
console.log(array); // ['Google', 'Naver']
console.log(array2); // ['Google', 'Naver', 'Tistory']
이 외에도 concat 메소드를 사용해서 배열을 합치는 것도 대체할 수 있죠.
const arr1 = ['Google','Naver','Tistory'];
const arr2 = ['Explorer', 'Firefox', 'Bing'];
const arr3 = [...arr1, ...arr2];
const arr4 = arr1.concat(arr2);
console.log(arr3); // ['Google', 'Naver', 'Tistory', 'Explorer', 'Firefox', 'Bing']
console.log(arr4); // ['Google', 'Naver', 'Tistory', 'Explorer', 'Firefox', 'Bing']
또한 함수에 여러개의 파라미터가 있는 경우에 배열을 펼쳐서 arguments로 사용할 수도 있습니다.
function print (first, second, third)
{
console.log(first, second, third)
}
const arr = [3,4,5]
print(...arr); //3 4 5
그런데 Spread구문은 한 가지 주의할 점이 있는대요. 하나의 값을 가진 배열을 펼칠 경우에는 에러가 발생합니다.
const numbers= [1];
const number = ...numbers; //Uncaught SyntaxError: Unexpected token '...'
Spread구문은 하나로 묶인 값을 여러 개로 펼친 개념이기 때문에 하나의 값으로 평가되는 게 아니라 목록의 값으로 평가되기 때문에 이런 문제가 발생하는 것입니다.
객체로의 활용
ES2018이후로 객체에도 Spread 구문을 사용할 수 있다는 표준이 등장함으로써 객체에서도 Spread구문을 사용할 수 있게 되었습니다. 현재는 기존의 객체를 가지고 새로운 객체를 만들 때 Spread 구문을 사용이 가능합니다.
const cat = {
name: 'Gorong',
};
const catClone = {
...cat,
age : 6,
}
console.log(cat); // {name: 'Gorong'}
console.log(catClone); // {name: 'Gorong', age: 6}
객체를 spread하는 걸로 새로운 배열이나 함수의 아규먼트로 사용이 불가능함.
const cat = {
name: 'Gorong',
};
const catClone = {
...cat,
age : 6,
}
[...cat]; // Uncaught SyntaxError
(function meow(...args) {
console.log(args);
})(...catClone); // Uncaught TypeError
'JS' 카테고리의 다른 글
[JS] 구조 분해(Destructuring) (0) | 2023.04.05 |
---|---|
[JS] 옵셔널 체이닝(Optional Chaining) (0) | 2023.04.03 |
[JS] 조건부 연산자(Conditional operator) (0) | 2023.03.31 |
[JS] 화살표 함수(Arrow Function) (0) | 2023.03.31 |
[JS] 나머지 파라미터(Rest Parameter) (0) | 2023.03.30 |