What is a Map function

A Map is a new data structure in ES6. A Map is similar to an object, but the key of an object must be a string or a number. A Map key can be any data type… Map is used in the same way as a normal object. Let’s take a look at the non-string or numeric key feature.

const map = new Map(a);const obj = {p: 'Hello World'};

map.set(obj, 'OK')
map.get(obj) // "OK"

map.has(obj) // true
map.delete(obj) // true
map.has(obj) // false
Copy the code

Map instance properties and methods:

  • Size: Gets the number of members
  • Set: Sets the member key and value
  • Get: Gets the value of a member attribute
  • Has: Checks whether a member exists
  • Delete: deletes a member
  • Clear: Clears all information
const map = new Map(a); map.set('aaa'.100);
map.set('bbb'.200);

map.size / / 2

map.get('aaa') / / 100

map.has('aaa') // true

map.delete('aaa')
map.has('aaa') // false

map.clear()
Copy the code

The Map instance traversal methods are:

  • Keys () : returns a traverser for key names.
  • Values () : Iterator that returns key values.
  • Entries () : Returns a traverser for all members.
  • ForEach () : traverses all Map members.
const map = new Map(a); map.set('aaa'.100);
map.set('bbb'.200);

for (let key of map.keys()) {
  console.log(key);
}
// "aaa"
// "bbb"

for (let value of map.values()) {
  console.log(value);
}
/ / 100
/ / 200

for (let item of map.entries()) {
  console.log('= = = = = = = =');
  console.log(item);
  console.log(item[0], item[1]);
}
/ / = = = = = = = =
// (2) ["aaa", 100]
// aaa 100
/ / = = = = = = = =
// (2) ["bbb", 200]
// bbb 200


map.forEach((value, key) = > {
    console.log(value, key)
})
// 100 "aaa"
// 200 "bbb"
Copy the code