Map Typescript Example with Explanations
Question: Can you provide an example of using maps in TypeScript with explanations?
Answer:
Certainly! In TypeScript, a Map is a collection of key-value pairs where each key and value can be of any data type. Here's an example with explanations:
typescript// Creating a new Map
let myMap = new Map();
// Adding key-value pairs to the Map
myMap.set("name", "John");
myMap.set("age", 25);
myMap.set("isStudent", true);
// Accessing values using keys
console.log(myMap.get("name")); // Output: John
console.log(myMap.get("age")); // Output: 25
console.log(myMap.get("isStudent")); // Output: true
// Checking if a key exists in the Map
console.log(myMap.has("name")); // Output: true
console.log(myMap.has("gender")); // Output: false
// Deleting a key-value pair from the Map
myMap.delete("age");
// Iterating through the Map using forEach
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
/*
Output:
name: John
isStudent: true
*/
// Checking the size of the Mapconsole.log(myMap.size); // Output: 2
Explanation:
Creating a Map:
- We create a new Map using the
Map
constructor:let myMap = new Map();
- We create a new Map using the
Adding key-value pairs:
- We use the
set
method to add key-value pairs to the Map.
- We use the
Accessing values:
- The
get
method is used to retrieve the value associated with a specific key.
- The
Checking key existence:
- The
has
method is used to check if a key exists in the Map.
- The
Deleting key-value pairs:
- The
delete
method removes a key-value pair based on the provided key.
- The
Iterating through the Map:
- We use the
forEach
method to iterate over the key-value pairs in the Map.
- We use the
Checking the size:
- The
size
property gives the number of key-value pairs in the Map.
- The
This example demonstrates the basic operations you can perform with a Map in TypeScript. Maps are versatile and provide an efficient way to manage key-value data.
0 মন্তব্যসমূহ