Typescript에서 Map 사용하기

He SEO·2022년 6월 24일

Map 함수

함수설명
map.set(key, value)값 세팅 (key, value)
map.has(key)키값이 있는지 확인
map.get(key)키값의 value 가져오기
map.delete(key)키값의 value 삭제
map.clear()값 전체 삭제
map.size맵 크기 반환
map.keys()맵의 키값만 반환
map.values()맵의 값만 반환
  • loop 문 : [for...of] 사용

Map 생성

let map = new Map<string, number>();

값 세팅

map.set("Gildong", 1);
map.set("Sejong", 2);
map.set("Esme", 3);

값 확인

for (let [key, value] of map) {
    console.log("key : " + key + ", value : " + value);
}
// Result : 
// key : Gildong, value : 1
// key : Sejong, value : 2
// key : Esme, value : 3

키값이 있는지 확인

if (map.has("Gildong")) console.log("Gildong OK");
else console.log("Gildong Fail");
if (map.has("Superman")) console.log("Superman OK");
else console.log("Superman Fail");

// Result : 
// Gildong OK
// Superman Fail

맵의 크기 확인

console.log("size is : " + map.size);
// size is : 3

맵의 키 삭제

map.delete("Sejong");
for (let [key, value] of map) {
    console.log("key : " + key + ", value : " + value);
}
// Result :
// key : Gildong, value : 1
// key : Esme, value : 3

참고 사이트

profile
BACKEND 개발 기록 중. 감사합니다 😘

0개의 댓글