ES6 new features: Map and Weakmap objects in JavaScript

Source: Internet
Author: User

Map Object

The Map object is an object with corresponding key/value pairs, and JS object is also a key/value pair.

There are several differences in ES6 in the map relative to object objects:

1: Objecthas a prototype , that is, he has a default key value above the object, unless we use object.create (NULL) to create an object without a prototype;
2: in object, only String and symbol are the key values , but in map, the key value can be any basic type (string, number, Boolean, undefined, NaN ...), or object (Map, Set, Object, Function, Symbol, null ...);
3: Through the Size property in the map , it is easy to get to the map length, to get the length of the object, you can only use other methods;
The key value of the map instance object can be an array or an object, or a function, and the ordering of the data in the map object instance is sorted according to the order of the user push, and the key in the object instance , The order of value is somewhat regular, (they will first rank the key value at the beginning of the number, then the key value at the beginning of the string);

Properties of the Map instance

Map.size This property and the length of the array is a meaning that represents the current instance's lengths;

Methods for map Instances

  Clear () method to remove all key/value pairs;
  Delete (key)to remove the specified key/value pair;
  entries () returns an iterator that returns [key, value] in the order in which the objects are inserted;
  A ForEach (callback, context) loop executes a function and takes a key/value pair as a parameter;
  get (Key) returns the value values corresponding to the Map object key;
  Has (key) returns a Boolean value that returns whether the map object has a specified key;
  keys () returns an iterator that returns each key element in the order in which it was inserted;
  Set (key, value) sets the Key/value key/value pair to the Map object, which returns the Map object (the method of adding elements relative to the JavaScript Set,set object is called Add, and the map object adds elements to the method set;
  [@ @iterator] , like the Entrieds () method, returns an iterator that returns [key, value] in the order in which the objects are inserted;

Simulate a map constructor yourself:

Now that we know the methods and properties of the map object, we can also simulate a map constructor ourselves, which requires the support of the generator, so it is necessary to use a patch for the generator in ES5 (simulating the set constructor):

"Utf-8">"Use Strict"; classMap {/** * @param [[key, value], [K, Val]];             * @return void; */            StaticRefresh (ARG) { for(let [key,value] of Arg) {//the judgment is repeated;Let index = Map.has.call ( This, key); if(index===false) {                         This. _keys.push (key);  This. _values.push (value); }Else{                        //If there is a duplicate value, then we perform the overwrite;                         This. _keys[index] =key;  This. _values[index] =value;                }                };  This. Size = This. _keys.length; }            /** * @desc return False | | number; **/            StaticHas (key) {varindex = This. _keys.indexof (key); if(Index = = =-1) {                    return false; }Else{                    returnindex;            }; } constructor (Arg) { This. _keys = [];  This. _values = []; Map.refresh.call ( This, ARG); }            Set(key, value) {Map.refresh.call ( This, [[Key,value]]); return  This; } clear () { This. _keys = [];  This. _values = []; return  This; } Delete (key) {varindex = Map.has.call ( This, key); if(index!==false) {                     This. _keys.splice (Index,1);  This. _values.splice (Index,1);                }; return  This; } entries () {return  This[Symbol.iterator] (); } has (key) {returnMap.has.call ( This, key) = = =false?false:true; }            *keys () { for(Let K of This. _keys) {                    yieldK; }            }            *values () { for(Let V of This. _values) {                    yieldv; }            }            //It is convenient to use the foreach array directly;ForEach (FN, context) {return  This; }            //you must support the builder's notation;*[Symbol.iterator] () { for(varI=0; i< This. _keys.length; i++) {                    yield[ This. _keys[i], This. _values[i]];        }            }        }; varMap =NewMap ([["Key","value"]]); Map.Set("Heeh","Dada"); Console.log (Map.has ("Key"));//output: true;Map.delete ("Key"); Console.log (Map.has ("Key"));//output: false;Map.Set("Key","value"); varKeys =Map.keys (); varValues =map.values ();        Console.log (Keys.next ());        Console.log (Keys.next ());        Console.log (Values.next ());        Console.log (Values.next ()); varEntries =map.entries ();    Console.log (entries); </script></body>View CodeMap using Demo:
varMyMap =NewMap ();varKeyString ="A String", Keyobj={}, Keyfunc=function () {};//we set the value for Mymap .MyMap.Set(KeyString,"String '"); MyMap.Set(Keyobj,"Object"); MyMap.Set(Keyfunc,"function"); mymap.size; //Output Length: 3//Get ValueConsole.log (MyMap.Get(keystring));//Output: StringConsole.log (MyMap.Get(Keyobj));//Output: ObjectConsole.log (MyMap.Get(Keyfunc));//Output: FunctionConsole.log (myMap.Get("A String"));//Output: StringConsole.log (myMap.Get({}));//Output: UndefinedConsole.log (MyMap.Get(function () {}))//Output: Undefined

We can also put nan,undefined, objects, arrays, functions , and so on as a key value for a map object:

" Use Strict "  New  map (); map. Set " 0 " ); map. Set  // output: Map {undefined = ' 0 ', NaN = {}}
How to Loop Map

A foreach method using a map instance;

" Use Strict "  New  map (); map. Set " 0 " ); map. Set (NaN, {}); Map.foreach (function (value, key, map) {    Console.log (key,value, map);});

Using the For...of loop:

" Use Strict "  New  map (); map. Set " 0 " ); map. Set (NaN, {});  for (Let [key, value] of map) {    Console.log (key, value);}  for (let arr of map) {    console.log (arr);}
Weakmap

Weakmap is a weakly referenced map object, and if the object does not exist in the JS execution environment, the object within the corresponding Weakmap object will also be recycled by JS execution environment;

Properties of the Weakmap object: None

Methods for Weakmap objects:

  Delete (key): deletes the specified key/value pair;

  get (Key): returns the value values corresponding to the Map object key;

  Has (key): Returns a Boolean value that actually returns whether the map object has a specified key;

  Set (key): sets the Key/value key/value pair to the Map object and returns the Map object;

Weakmap a lot less than map, we can also implement these methods ourselves, for example, we will implement a map instance of the Clear method:

classClearableweakmap {Constructor (init) { This. _WM =Newweakmap (Init)} clear () { This. _WM =Newweakmap ()} delete (k) {return  This. _wm.delete (k)}Get(k) {return  This. _wm.Get(k)} has (k) {return  This. _wm.has (k)}Set(k, v) { This. _wm.Set(k, v)return  This  }}

  

Reference:

Mdn:https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/map;

ruanyifeng:http://es6.ruanyifeng.com/#docs/set-map

NONO
Source: http://www.cnblogs.com/diligenceday/
QQ: 287101329
: 18101055830

ES6 new features: Map and Weakmap objects in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.