TypeScript Map object

1. Create a map

let myMap = new Map();

2. Properties

2.1 size

Returns the number of key/value pairs in the Map object

3. Function

  • map.clear() – removes all key/value pairs from a Map object.
  • map.set() – set the key-value pair and return the Map object.
  • map.get() – returns the value corresponding to the key, or undefined if it does not exist.
  • map.has() – Returns a Boolean value used to determine whether the Map contains the value corresponding to the key.
  • map.delete() – deletes the elements in the Map, returns true if the deletion is successful, and returns false if it fails.
  • map.keys() - Returns an Iterator object containing the keys for each element in the Map object.
  • map.values() – returns a new Iterator object containing the values ​​of each element in the Map object.
  • entries() - returns a tuple [key, value]
let map = new Map();
map.set("key1", 1);
map.set("key2", 2);
map.set("key3", 3);

console.log(map.get("key1"));       // 1
console.log(map.has("key2"));       // true
console.log(map.has("key4"));       // false
console.log(map.size);              // 3
console.log(map.delete("key3"));    // true
console.log(map.size);              // 2
map.clear();    
console.log(map);                   // Map(0){size = 0}

4. traverse

let map = new Map();
map.set("key1", 1);
map.set("key2", 2);
map.set("key3", 3);

map.forEach((val, key, map) => {
    
    console.log(val, key)});	
// 1 'key1'		2 'key2'  	3 'key3'

Guess you like

Origin blog.csdn.net/weixin_45136016/article/details/130111512