Map
Initialization
var roles = new Map([
['r1', 'User'],
['r2', 'Guest'],
['r3', 'Admin'],
]);
console.log(typeof(roles)); //object
console.log(roles);
Methods
var m = new Map();
// set
m.set("name", "Lin");
m.set("age", 39);
// get
console.log(m.get("name"));
// size
console.log(m.size);
// has
console.log(m.has("name"));
var m = new Map();
// set chains
m.set("name", "Lin").set("age", 39);
console.log(m)
var roles = new Map([
['r1', 'User'],
['r2', 'Guest'],
['r3', 'Admin'],
]);
// delete
console.log(roles.delete('r1')); // true
console.log(roles);
// entries
var itr = roles.entries(); // iterator object
for (const [key, value] of itr) {
console.log(key, value);
}
// forEach
roles.forEach((value, key) => console.log(value));
// keys
var keys = roles.keys(); // iterator object
for (const key of keys)
console.log(roles.get(key));
// values
var values = roles.values(); // iterator object
for (const value of values)
console.log(value);
// clear
roles.clear();
WeakMap
Its keys must be objects
Keys in a weak map can be Garbage collected. Garbage collection is a process of clearing the memory occupied by unreferenced objects in a program
A weak map cannot be iterated or cleared
let weakMap = new WeakMap();
let obj = {};
let obj2 = {name: 'Lin'};
weakMap.set(obj, 'hello');
weakMap.set(obj2, 39);
console.log(weakMap);
console.log(weakMap.has(obj));
console.log(weakMap.get(obj2));