This is the 13th day of my participation in the August More Text Challenge.More challenges in August

The Map object holds key-value pairs and can remember the original insertion order of the keys. Any value (object or raw value) can be a key or a value. Map is a new data structure introduced in ES6. For details, see ES6 Map and Set.

Create a map

let myMap = new Map();
Copy the code

or

let myMap = new Map([
        ["key1", "value1"],
        ["key2", "value2"]
]);
Copy the code

Map-related functions and attributes:

  • Map.clear (): Removes all key/value pairs of the map object.
  • Map.set (): Sets the key-value pair and returns the map object.
  • Map.get (): returns the value of the key, or undefined if none exists.
  • Map.has (): Returns a Boolean value that determines whether the map contains a value for a key.
  • Map.delete (): deletes elements from a map. Returns true on success and false on failure.
  • Map. size: Returns the number of key/value pairs in the Map object.
  • Map.keys (): Returns an Iterator containing the keys of each element in the map.
  • Map.values (): Returns a new Iterator containing the values of each element in the map.

Code examples:

// 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; // } // interface MapConstructor { // new(): Map<any, any>; // new<K, V>(entries? : readonly (readonly [K, V])[] | null): Map<K, V>; // readonly prototype: Map<any, any>; // } // declare var Map: MapConstructor; let myMap = new Map(); // set mymap.set ('name', 'ZZH '); myMap.set('height', '172'); myMap.set('age', '18'); Console. log(mymap.get ('name')); // ZZH // check whether a key console.log(mymap.has ('name')) is included; // true console.log(myMap.keys()); //[Map Iterator] { 'name', 'height', 'age' } console.log(myMap.values()); // [Map Iterator] { 'zzh', '172', '18' } console.log(myMap.size); // 3 // zzh:name // 172:height // 18:age myMap.forEach((key, value) => console.log(`${key}:${value}`)); myMap.delete('height'); // zzh:name // 18:age myMap.forEach((key, value) => console.log(`${key}:${value}`)); myMap.clear(); / / no output myMap. ForEach ((key, value) = > console. The log (` ${key} : ${value} `));Copy the code