TypeScript에서 Map(자료구조) 을 사용하는 방법을 알아본다
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
readonly size: number;
}
const map = new Map();
const mapWithType = new Map<string, any[]>();
const map = new Map<string, string[]>();
map.set('keyOne', ['value1', 'value2']);
map.set('keyTwo', ['value1', 'value2', 'value3']);
map.set('keyThree', ['value1', 'value2', 'valu3', 'value4']);
// Update
map.set('keyTwo', ['value1']);
console.log(`DELETE(KEY IS EXIST): ${map.delete('keyTwo')}`);
console.log(`DELETE(KEY IS NOT EXIST): ${map.delete('keyFour')}`);
[Result]
DELETE: true
DELETE: false
map.clear();
console.log(`GET(KEY IS EXIST): ${map.get('keyOne')}`);
console.log(`GET(KEY IS NOT EXIST): ${map.get('keyFour')}`);
[Result]
GET: value1,value2
GET: undefined
console.log(`KEY IS EXIST: ${map.has('keyOne')}`);
console.log(`KEY IS NOT EXIST: ${map.has('keyFour')}`);
[Result]
true
false
const mapKeys = map.keys();
for (const key of mapKeys) {
console.log(`KEY: ${key}`);
}
[Result]
KEY: keyOne
KEY: keyTwo
KEY: keyThree
const mapValues = map.values();
for (const value of mapValues) {
console.log(`VALUES: ${value}`);
}
[Result]
VALUES: value1,value2
VALUES: value1,value2,value3
VALUES: value1,value2,valu3,value4
const map = new Map<string, string[]>();
map.set('keyOne', ['value1', 'value2']);
map.set('keyTwo', ['value1', 'value2', 'value3']);
map.set('keyThree', ['value1', 'value2', 'valu3', 'value4']);
for (const [key, values] of map) {
console.log(`KEY: ${key}, VALUE: ${values}`);
}
const mapArrays = Array.from(map);
for (const item of mapArrays) {
console.log(`KEY: ${item[0]}, VALUE: ${item[1]}`);
}
for (const [key, values] of mapArrays) {
console.log(`KEY: ${key}, VALUE: ${values}`);
}
const mapEntries = map.entries()
for (const item of mapEntries) {
console.log(`KEY: ${item[0]}, VALUE: ${item[1]}`);
}
for (const [key, values] of mapEntries) {
console.log(`KEY: ${key}, VALUE: ${values}`);
}
[Result]
KEY: keyOne, VALUE: value1,value2
KEY: keyTwo, VALUE: value1,value2,value3
KEY: keyThree, VALUE: value1,value2,valu3,value4
const map = new Map<string, string[]>();
map.set('keyOne', ['value1', 'value2']);
map.set('keyTwo', ['value1', 'value2', 'value3']);
map.set('keyThree', ['value1', 'value2', 'valu3', 'value4']);
// obj === map
map.forEach((values, key, obj) => {
console.log(`KEY: ${key}, VALUE: ${values}`);
});
[Result]
KEY: keyOne, VALUE: value1,value2
KEY: keyTwo, VALUE: value1,value2,value3
KEY: keyThree, VALUE: value1,value2,valu3,value4