es6 foundation 0x012: Map

Keywords: Javascript

0x000 overview

MapIt is also a new data structurejsIn fact, it is often used, such as the following chestnut. We often use an object like this. It is more like an object than an objectMap,But compared to the realMap,This one is still a little weak,

let color={
    "red":"#FF0000",
    "green":"#00FF00",
    "blue":"#0000FFF"
}
color['red']

0x001 initialization

new Map([iterable])

Initialization of a Map has an optional parameter, which must be an iterative object, including String, Array, Array like object (arguments, NodeList), typed Array, Set, Map and user-defined iterative object.

  • array

    new Map([[1,2],[3,4]]) // Map(2) {1 => 2, 3 => 4}

0x002 add

Compared with object as Map, the key of Map can be any value, even NaN

var myMap = new Map();
 
var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";
 
// Add key
myMap.set(keyString, "Sum key'a string'Associated values");
myMap.set(keyObj, "Sum key keyObj Associated values");
myMap.set(keyFunc, "Sum key keyFunc Associated values");

0x003 get Map size

myMap.size    // 3

0x004 acquisition

myMap.get(keyString)   // "Value associated with key 'a string'"
myMap.get(keyObj)     // "Value associated with key keyObj"
myMap.get(keyFunc)      // "Value associated with key keyFunc"

0x005 include

myMap.has(keyString)  // true
myMap.has('1')  // false

0x006 delete

myMap.delete(keyString)  // true
myMap.delete('')  // false

0x007 traversal

myMap.forEach(m=>{console.log(m)})
// Value associated with key 'a string'
//  Value associated with key keyObj
//  Value associated with key keyFunc

0x008 get iterator

let entries=myMap.entries()
entries.next().value // Value associated with key 'a string'
entries.next().value//  Value associated with key keyObj
entries.next().value//   Value associated with key keyFunc

0x009 get key iterator

let keys=myMap.keys()
keys.next().value //  "a string"
keys.next().value//  function () {}
keys.next().value//   {}

0x010 get value iterator

let values=myMap.values()
values.next().value // Value associated with key 'a string'
values.next().value//  Value associated with key keyObj
values.next().value//   Value associated with key keyFunc

0x011 clear

mySet.clear()

Posted by matthewdingley on Mon, 09 Dec 2019 21:54:50 -0800