JavaScript/TypeScript 기본 문법: Spread, Rest, Map 사용법 예제 총정리
초보자를 위한 JS/TS 문법: Spread, Rest, Map 완전 정복
spread
, rest
, map
모두 JavaScript/TypeScript의 기본 문법입니다. Vue 코드에서 자주 쓰여요.
1. Spread 문법 (...obj
)
객체나 배열을 “펼치는” 문법
문법 예시 (객체)
const user = { name: 'Alice', age: 25 };
const newUser = { ...user, age: 30 };
console.log(newUser);
// 👉 { name: 'Alice', age: 30 }
...user
는 기존 속성 전부 복사- 뒤에서
age: 30
으로 덮어씀
배열 예시
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4];
console.log(arr2);
// 👉 [1, 2, 3, 4]
2. Rest 문법 (...rest
)
여러 개의 값을 “하나의 변수로 수집”
함수 매개변수에서 사용
function sum(...numbers: number[]) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 👉 6
...numbers
: 여러 개의 숫자 인자를 배열로 수집
구조 분해할당에서 사용
const { name, ...rest } = { name: 'Alice', age: 25, job: 'dev' };
console.log(rest);
// 👉 { age: 25, job: 'dev' }
3. map()
함수
배열을 “새로운 배열로 변환”하는 메서드
예시
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
console.log(doubled);
// 👉 [2, 4, 6]
- 각
n
에 대해n * 2
를 실행하고 새 배열 생성
🎯 차이 요약
문법 | 역할 | 예시 |
---|---|---|
...obj | spread: 펼치기 | { ...user, age: 30 } |
...args | rest: 모으기 | function fn(...args) {} |
.map() | 배열 변환 | [1,2,3].map(n => n * 2) |
💡 TypeScript와 Vue와의 관계
항목 | 관련성 |
---|---|
Spread / Rest / Map | ✅ JavaScript(ES6+) / TypeScript 문법 |
TypeScript | ✅ 지원하며 타입 검사도 해줌 (e.g., ...args: number[] ) |
예: Vue 컴포지션 API에서 활용
const list = ref<User[]>([]);
list.value = users.map(user => ({
...user,
name: user.name.toUpperCase()
}));
이런 식으로 JavaScript 문법을 Vue 컴포지션 API와 함께 사용하는 것입니다.
실습해볼 예제 코드
1. Spread 문법 실습
// 🌟 객체 Spread
const user = { name: 'Alice', age: 25 };
const newUser = { ...user, age: 30, job: 'Developer' };
console.log("Original:", user);
console.log("New:", newUser);
// 👉 New: { name: 'Alice', age: 30, job: 'Developer' }
// 🌟 배열 Spread
const fruits = ['🍎', '🍌'];
const moreFruits = [...fruits, '🍇'];
console.log("Fruits:", moreFruits);
// 👉 ['🍎', '🍌', '🍇']
2. Rest 문법 실습
// 🌈 함수에서 Rest
function greetAll(...names: string[]) {
names.forEach(name => console.log(`Hello, ${name}!`));
}
greetAll('Alice', 'Bob', 'Charlie');
// 👉 Hello, Alice!
// 👉 Hello, Bob!
// 👉 Hello, Charlie!
// 🌈 구조 분해에서 Rest
const person = { name: 'Alice', age: 30, country: 'Korea' };
const { name, ...others } = person;
console.log(name); // Alice
console.log(others); // { age: 30, country: 'Korea' }
3. map() 실습
const numbers = [1, 2, 3, 4];
// 각 숫자를 제곱해서 새 배열 생성
const squares = numbers.map(n => n * n);
console.log("Original:", numbers); // [1, 2, 3, 4]
console.log("Squares:", squares); // [1, 4, 9, 16]
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob']
🧪 Vue 3 컴포지션 API 예제 (TypeScript + ref
, map
, spread
, rest
)
🛠 예제: 사용자 목록을 변형해서 표시하기
<script setup lang="ts">
import { ref } from 'vue'
// 1. 사용자 목록 데이터 (원본)
const rawUsers = ref([
{ id: 1, name: 'Alice', age: 25, phone: '01012345678' },
{ id: 2, name: 'Bob', age: 30, phone: '01098765432' }
]);
// 2. 전화번호 포맷 함수 (01012345678 → 010-1234-5678)
function formatPhone(phone: string): string {
return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
}
// 3. 사용자 목록 가공 (map + spread + format)
const formattedUsers = ref(
rawUsers.value.map(user => {
const { phone, ...rest } = user; // rest 사용: phone 제외 나머지 모음
return {
...rest, // spread 사용: name, age 등 복사
phone: formatPhone(phone) // phone 포맷 변경
}
})
);
</script>
<template>
<h2>사용자 목록 (포맷된)</h2>
<ul>
<li v-for="user in formattedUsers" :key="user.id">
{{ user.name }} ({{ user.age }}세) - 📞 {{ user.phone }}
</li>
</ul>
</template>
코드 요약
문법 | 사용 위치 | 설명 |
---|---|---|
ref | 상태 선언 | Vue의 반응형 상태 |
map() | 배열 가공 | 사용자 배열 가공 |
...rest | 구조분해 | phone 제외 나머지 속성 모음 |
...rest in return | spread | 기존 속성 복사 |
formatPhone | 함수 | 문자열 포맷 변경 |