TypeScript Map Method Details
In TypeScript, Map is a collection type used to store key-value pairs. Similar to Set, keys and values in a Map can be of any type, and each key can appear only once.
The syntax for defining a Map is as follows:
let myMap = new Map<string, number>();
Here, myMap is an empty Map that can store key-value pairs where the keys are string types and the values are number types. You can also specify initial values when creating a Map, for example:
let myMap = new Map<string, number>([
["a", 1],
["b", 2],
["c", 3]
]);
In this case, myMap contains three key-value pairs: "a": 1, "b": 2, and "c": 3.
The Map object provides a series of methods for operations such as adding, deleting, and retrieving elements. For example, you can use the set() method to add new key-value pairs to a Map, the delete() method to remove key-value pairs, and the get() method to retrieve the value corresponding to a key. For example:
let myMap = new Map<string, number>();
myMap.set("a", 1); // Add key-value pair "a": 1 to the Map
myMap.set("b", 2); // Add key-value pair "b": 2 to the Map
myMap.set("c", 3); // Add key-value pair "c": 3 to the Map
myMap.delete("b"); // Remove the key-value pair with key "b" from the Map
console.log(myMap.get("a")); // Output: 1
console.log(myMap.get("b")); // Output: undefined
The Map object can also use the forEach() method to iterate over key-value pairs in the collection. For example:
let myMap = new Map<string, number>([
["a", 1],
["b", 2],
["c", 3]
]);
myMap.forEach(function(value, key) {
console.log(key + " = " + value);
});
// Output:
// a = 1
// b = 2
// c = 3
Note that keys in a Map must be unique. Therefore, if you add duplicate keys to a Map, the subsequent value will overwrite the previous one. Additionally, there is no specific order for key-value pairs in a Map, so elements cannot be accessed using an index. If you need to access key-value pairs in a specific order, you can convert the Map to an array and then perform operations on it.