In JavaScript, you can create a new Map
using the Map
constructor. The Map
constructor takes an optional iterable object as an argument and creates a new map from it. Here’s an example:
const map = new Map([
['firstName', 'John'],
['lastName', 'Doe']
]);
console.log(map); // outputs: Map { 'firstName' => 'John', 'lastName' => 'Doe' }
In this example, the Map
constructor is called with an array of arrays as its argument. Each inner array represents a key-value pair in the map. The resulting map
object is a new Map
with two key-value pairs: 'firstName' => 'John'
and 'lastName' => 'Doe'
.
You can also add key-value pairs to a Map
after it has been created, using the set
method. Here’s an example:
const map = new Map();
map.set('age', 30);
map.set('gender', 'male');
console.log(map); // outputs: Map { 'age' => 30, 'gender' => 'male' }
In this example, a new Map
is created using the Map
constructor without any arguments. Two key-value pairs are added to the map using the set
method.
+ There are no comments
Add yours