이번주에 걷기반에서 배운 스프레드연산자에 대해 궁금증이 생겼다.
스프레드연산자와 리스트연산자의 차이점이 대체 뭘까??
Spread연산자
//배열
const fruits = ['apple', 'banana', 'orange'];
const moreFruits = [...fruits, 'grape', 'mango'];
console.log(moreFruits); // ["apple", "banana", "orange", "grape", "mango
//객체
const person = {
name: 'Alice',
age: 25
};
const updatedPerson = {
...person,
city: 'Seoul'
};
console.log(updatedPerson); // { name: 'Alice', age: 25, city: 'Seoul' }
위 코드는 구조분해할당에 대해 잘 안다면 이해할 것이다.
rest연산자
//배열
const fruits = ['apple', 'banana', 'orange', 'grape'];
// 첫 번째와 나머지를 분리
const [first, ...rest] = fruits;
console.log(first); // "apple"
console.log(rest); // ["banana", "orange", "grape"]
//객체
const person = {
name: 'Alice',
age: 25,
city: 'Seoul'
};
// name과 나머지를 분리
const { name, ...otherInfo } = person;
console.log(name); // "Alice"
console.log(otherInfo); // { age: 25, city: 'Seoul' }
위 코드 또한 구조분해할당을 안다면 이해할 것이다.
얼핏보면 정말 비슷한 두 개념의 차이점에 대해 공부했다
spread연산자는 배열이나 객체를 펼칠 때 사용하고 rest연산자는 매개변수에서 여러 인수를 배열로 받을 때 사용한다.
const sum = (...numbers) => {
// reduce 메서드는 배열의 각 요소를 누적하여 하나의 값을 반환
return numbers.reduce((acc, curr) => acc + curr, 0);
};
// sum(1, 2, 3, 4) -> [1, 2, 3, 4]
목적
- Spread 연산자의 목적
- 기존의 배열이나 객체를 복사하고, 새로운 요소를 추가하거나 수정하여 새로운 배열이나 객체를 생성하는 것입니다. 데이터를 전개하여 사용합니다.
- Rest 연산자의 목적
- 함수에 전달된 여러 개의 인수를 배열로 묶어, 이를 함수 내부에서 쉽게 처리할 수 있게 하는 것입니다. 입력값을 수집하는 데 사용합니다.
'sparta > 본캠프' 카테고리의 다른 글
[textContent] (1) | 2024.10.26 |
---|---|
[reduce] (0) | 2024.10.26 |
[구조분해할당] (0) | 2024.10.26 |
[주말]자바스크립트 최종 (두고두고 볼 내용) (0) | 2024.10.26 |
[본캠프]19일차 (0) | 2024.10.25 |