
📅 2025-09-24
➡️ JavaScript Map, Set에 대해 새롭게 알게 된 것 또는 헷갈리는 부분 정리
Date 객체를 사용하면 날짜와 시간에 관한 정보를 얻을 수 있음// 1) 현재 시각
const now = new Date();
console.log(now);
// 2) 기준(1970-01-01 UTC)으로부터 밀리초 경과
const d1 = new Date(0); // 기점에서 0초 경과
console.log(d1);//Thu Jan 01 1970 09:00:00 GMT+0900 (한국 표준시)
// 1일 = 86,400,000 ms
const d2 = new Date(86400000);
console.log(d2); // Fri Jan 02 1970 09:00:00 GMT+0900 (한국 표준시)
// 3) 문자열 파싱
const d3 = new Date("2020-05-10 12:30:00");
console.log(d3); //Sun May 10 2020 12:30:00 GMT+0900 (한국 표준시)
// 4) 직접 숫자 지정 (연, 월, 일, 시, 분, 초, ms)
const d4 = new Date(2020, 4, 10, 12, 30, 0); // Sun May 10 2020 12:30:00 GMT+0900 (한국 표준시)
console.log(d4);
const today = new Date();
//현재 년도 가져오기
today.getFullYear(); // YYYY
// 년도 저장
today.setFullYear(2000);
//년도 월 일 지정
today.setFullYear(2000, 10, 10);
const today = new Date();
// 오늘 날짜에 해당하는 월 가져오기
console.log(today.getMonth());
/// 월 지정
today.setMonth(0);
console.log(today.getMonth());
// 월/일 지정
today.setMonth(10, 4)// 10월 4일
const today = new Date();
// 오늘 날짜에 해당하는 일 가져오기
console.log(today.getDate());
// 날짜 지정
today.setDate(1);
console.log(today);
console.log(today.getDate());
const today = new Date();
// 시간 가져오기
today.getHours();
// 분 가져오기
today.getMinutes();
// 초 가져오기
today.getSeconds();
size 속성으로 요소 개수를 쉽게 확인할 수 있음기본 CRUD
set(key, value) - 데이터 추가 / 수정const userMap = new Map();
// 데이터 추가
userMap.set('홍길동', {age: 30, city: '서울'});
userMap.set('김철수', {age: 25, city: '부산'});
// 기존 키에 새 값 설정 (덮어쓰기)
userMap.set('홍길동', {age: 31, city: '서울'});
console.log(userMap.get('홍길동')); // {age: 31, city: '서울'}get(key) - 데이터 조회const statusMap = new Map([
[200, 'OK'],
[404, 'Not Found'],
[500, 'Internal Server Error']
]);
console.log(statusMap.get(200)); // 'OK'
console.log(statusMap.get(404)); // 'Not Found'
console.log(statusMap.get(999)); // undefined (존재하지 않는 키)has(key) - 키 존재 여부 확인const colorMap = new Map([
['red', '#FF0000'],
['green', '#00FF00'],
['blue', '#0000FF']
]);
console.log(colorMap.has('red')); // true
console.log(colorMap.has('yellow')); // false
// 조건부 처리에 활용
if (colorMap.has('purple')) {
console.log(colorMap.get('purple'));
} else {
console.log('보라색은 정의되지 않았습니다.');
}delete(key) - 특정 요소 삭제const inventoryMap = new Map([
['laptop', 10],
['mouse', 25],
['keyboard', 15]
]);
console.log(inventoryMap.size); // 3
// 특정 항목 삭제
const deleted = inventoryMap.delete('mouse');
console.log(deleted); // true (삭제 성공)
console.log(inventoryMap.size); // 2
// 존재하지 않는 키 삭제 시도
const notDeleted = inventoryMap.delete('monitor');
console.log(notDeleted); // false (삭제 실패)clear() - 모든 요소 삭제const tempMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
console.log(tempMap.size); // 3
tempMap.clear();
console.log(tempMap.size); // 0
console.log(tempMap); // Map(0) {}set() 메서드는 Map 자신을 반환하므로 체이닝 가능const chainMap = new Map()
.set('first', 1)
.set('second', 2)
.set('third', 3);
console.log(chainMap); // Map(3) {"first" => 1, "second" => 2, "third" => 3}기본 반복 메서드
keys() - 키 반복const productMap = new Map([
['laptop', 1200],
['phone', 800],
['tablet', 600]
]);
console.log('=== 모든 제품명 ===');
for (const product of productMap.keys()) {
console.log(product);
}
// laptop, phone, tabletvalues() - 값 반복console.log('=== 모든 가격 ===');
for (const price of productMap.values()) {
console.log(`$${price}`);
}
// $1200, $800, $600entries() - 키 값 쌍 반복console.log('=== 제품과 가격 ===');
for (const [product, price] of productMap.entries()) {
console.log(`${product}: $${price}`);
}
// laptop: $1200, phone: $800, tablet: $600
// entries()는 기본 이터레이터이므로 생략 가능
for (const [product, price] of productMap) {
console.log(`${product}: $${price}`);
}forEach() 메서드const scoreMap = new Map([
['홍길동', 95],
['김철수', 87],
['김영희', 92]
]);
scoreMap.forEach((score, name, map) => {
const grade = score >= 90 ? 'A' : 'B';
console.log(`${name}: ${score}점 (${grade}등급)`);
});
// 홍길동: 95점 (A등급)
// 김철수: 87점 (B등급)
// 김영희: 92점 (A등급)const employeeMap = new Map([
['홍길동', {department: 'IT', salary: 5000}],
['김철수', {department: 'HR', salary: 4500}],
['홍길순', {department: 'IT', salary: 5500}],
['김영희', {department: 'Finance', salary: 4800}]
]);
// IT 부서 직원만 필터링
const itEmployees = new Map();
for (const [name, info] of employeeMap) {
if (info.department === 'IT') {
itEmployees.set(name, info);
}
}
console.log('IT 부서 직원들:');
itEmployees.forEach((info, name) => {
console.log(`${name}: $${info.salary}`);
});Set은 값만 저장하며, 키를 저장하지 않음특징
1. 고유성 : 중복된 값을 자동으로 제거
2. 순서 보장 : 값이 추가된 순서를 기억
3. 효율성 : 값 검색과 추가/삭제가 최적화 됨
4. 반복 가능 : forEach, for of 등으로 순회 가능
add(value) - 값 추가const userSet = new Set();
// 값 추가
userSet.add('이정은');
userSet.add('정윤진');
userSet.add('김미소');
// 중복 값 추가 시도
userSet.add('이정은'); // 무시됨
console.log(userSet); // Set(3) {'alice', 'bob', 'charlie'}
console.log(userSet.size); // 3
// 메서드 체이닝
const chainSet = new Set()
.add('first')
.add('second')
.add('third');
console.log(chainSet); // Set(3) {'first', 'second', 'third'}has(value) - 값 존재 확인const colorSet = new Set(['red', 'green', 'blue']);
console.log(colorSet.has('red')); // true
console.log(colorSet.has('yellow')); // false
console.log(colorSet.has('RED')); // false (대소문자 구분)
// 조건부 처리에 활용
if (colorSet.has('blue')) {
console.log('파란색이 있습니다!');
}
// 객체나 배열의 경우 참조 비교
const objSet = new Set();
const obj1 = {name: 'test'};
const obj2 = {name: 'test'};
objSet.add(obj1);
console.log(objSet.has(obj1)); // true (같은 참조)
console.log(objSet.has(obj2)); // false (다른 참조)`delete(value) - 값 삭제const animalSet = new Set(['cat', 'dog', 'bird', 'fish']);
console.log(animalSet.size); // 4
// 값 삭제
const deleted1 = animalSet.delete('dog');
console.log(deleted1); // true (삭제 성공)
console.log(animalSet); // Set(3) {'cat', 'bird', 'fish'}
// 존재하지 않는 값 삭제 시도
const deleted2 = animalSet.delete('elephant');
console.log(deleted2); // false (삭제 실패)
console.log(animalSet.size); // 3clear() - 모든 값 삭제const numberSet = new Set([1, 2, 3, 4, 5]);
console.log(numberSet.size); // 5
numberSet.clear();
console.log(numberSet.size); // 0
console.log(numberSet); // Set(0) {}size 속성const dynamicSet = new Set();
console.log(`초기 크기: ${dynamicSet.size}`); // 0
dynamicSet.add('a').add('b').add('c');
console.log(`추가 후 크기: ${dynamicSet.size}`); // 3
dynamicSet.delete('b');
console.log(`삭제 후 크기: ${dynamicSet.size}`); // 2
dynamicSet.clear();
console.log(`전체 삭제 후 크기: ${dynamicSet.size}`); // 0keys() 메서드set 안의 모든 값을 반환values() 메서드keys() 와 완벽하게 동일한 동작entries() 메서드set은 값을 저장만 하는데도 entries() 메서드는 [value, value] 형태로 반환let set = new Set(["oranges", "apples"]);
console.log([...set.keys()]); // ["oranges", "apples"]
console.log([...set.values()]); // ["oranges", "apples"]
console.log([...set.entries()]); // [["oranges","oranges"], ["apples","apples"]]