
오늘은 자바스크립트 spread와 rest에 대해 정리해보도록 할게요!
이터러블 객체를 개별값으로 나누는 펼침 연산자
...으로 표기
spread를 사용하면 객체나 배열을 펼쳐서 새로운 객체나 배열을 만들 수 있습니다.
아래 코드를 살펴보면 person01과 person02 두 객체 모두 country속성에 "KOREA"라는 값을 가지고 있습니다.
const person01 = {
country : "KOREA",
gender : "Female",
age : 25
};
const person02 = {
country : "KOREA",
gender : "Male",
age : 26
};
console.log(person01);
console.log(person02);
이러한 공통된 내용을 처리할 때 spread를 사용하면 좀 더 간편하게 코드를 작성할 수 있습니다.
const person01 = {
country : "KOREA",
gender : "Female",
age : 25
};
const person02 = {
...person01,
gender : "Male",
age : 26
};
console.log(person01); // { country: 'KOREA', gender: 'Female', age: 25 }
console.log(person02); // { country: 'KOREA', gender: 'Male', age: 26 }
또한, spread를 사용하면 객체를 복사하거나 기존 객체를 합쳐 새로운 객체를 만들 수 있습니다.
// person01객체를 person02에 복사
const person01 = {
country : "KOREA",
gender : "Female",
age : 25
};
const person02 = {...person01};
// person객체와 info객체를 합쳐 새로운 객체 생성
const person = {
country : "KOREA",
gender : "Female"
};
const info = {
name : "송우든",
age : 25
};
console.log({...info,...person});
// 출력 : { name: '송우든', age: 25, country: 'KOREA', gender: 'Female' }
매개변수 앞에
...을 붙여서 사용
반드시 마지막 파라미터여야함
여러개의 매개변수를 받는 함수를 호출할 때, ...으로 간단히 표현할 수 있는데요. 아래 코드에서는 1은 num1이라는 파라미터에 할당이 되고, 나머지 2부터 10은 rest파라미터에 순서대로 할당이 됩니다.
function calcNum(firstNum, ...rest) {
let sum = firstNum;
for (let num of rest) {
sum += num
}
console.log(`sum : ${sum}`)
}
calcNum(1,2,3,4,5,6,7,8,9,10); // 출력 : 55
나머지 파라미터들은 배열에 담겨 할당이 됨으로 for...of문으로 값을 빼올 수 있어요!
또한, rest가 아닌 다른 이름을 붙여서 사용할 수 있어요!
function calcNum(firstNum, ...nums) {
let sum = firstNum;
for (let num of nums) {
sum += num
}
console.log(`sum : ${sum}`)
}