A preface.


This article mainly talks about the usage of JS Map object and how to handwritten Map, very suitable for the preliminary study of JS students, appropriate learn to handwritten JS source code skills, JS understanding and interview have great help. Most people know the use of Map method, but on the Internet to Map source code implementation of the article is very few, I hope this article can help you to understand the Map method.

Said in the previous

The Map object holds key-value pairs and can remember the original insertion order of the keys. Any value (object or raw value) can be a key or a value. This article will give you a brief introduction to usage and then hand-written maps, so take a few minutes to read this article if you want to see a Map in its original form.


2. Use of Map method


A Map is a structure of key-value pairs with extremely fast lookup times.

For example, if you want to find a grade based on a student’s name, if you use Array, you need two arrays:

var names = ['lm'.'dz'.'xxy'];
var scores = [100, 90, 80];
Copy the code

To do this, we need to iterate through the Names array to find where we want to query the names of the students, and then retrieve the scores from the scores array. There are two disadvantages to this:

  1. The longer the array is, the longer the query takes.
  2. If there is a lot of data, it is easy to make errors when importing data.

If the Map implementation, only need a “name” – “score” comparison table, directly according to the name to find the score, a key (name) and a corresponding value (score) binding, no matter how big the table, do not worry about errors. Use JavaScript to implement Map as follows:

var m = new Map([['lm', 100], ['dz', 90], ['xxy', 80]]);
m.get('lm'); //100 m.size(); //3 m.set('xp', 90); // add a new key-value m.delelete ('xxy'); / / delete key'xxy'
Copy the code

Get Map to find lm student 100 points, use size to obtain how many key-value pairs, use set method to add XP results, use delete method to delete XXY results.

Note that a key can only correspond to one value. If you add a value to a key multiple times, the subsequent value will flush out the previous value:

var m = new Map();
m.set('xp', 70);
m.set('xp', 90);
m.get('xp'); / / 90Copy the code

3. Handwritten Map method

The first thing you need to know about the handwritten Map method is that it has a new data type for the ES6 standard, which is a collection of key/value pairs. There are many ways to manipulate this data type. Let us, a small hand knock, let it show its original form ~

  • Defining Map methods

    The first step to writing a method is, of course, to define it and declare its parameters.

/** ** Description: JS implementation map method * @returns {map} */function Map(){  
       var struct = function(key, value) {  
        this.key = key;  
        this.value = value;  
       }; 
   }
Copy the code
  • Write a set method

    We need to add a key-value pair. We need to note that if the key-value pair already exists, we need to update its value. If not, save the pair of keys directly.

// Add map key-value pair varset = function(key, value){// Traverses the number group, overwriting it if it existsfor (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
           this.arr[i].value = value;  
           return; }}; This.arr [this.arr. Length] = new struct(key, value); };Copy the code
  • Write the get method

    If the key exists, the corresponding value will be obtained; otherwise, null will be returned. The code is as follows:

Var get =function(key) {  
         for (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
           returnthis.arr[i].value; }}return null;  
        };  
Copy the code
  • Write the remove method

The Map method can be used to delete key-value pairs using keys. To delete key/value pairs, iterate through all arrays, regardless of whether they exist or not. Pop v. Key from the top of the stack, continue if the key to be deleted matches v.Key, otherwise unshift(v), restore it. The code is as follows:

Var remove = var remove =function(key) {  
         var v;  
         for (var i = 0; i < this.arr.length; i++) {  
          v = this.arr.pop();  
          if ( v.key === key ) {  
           continue; } this.arr.unshift(v); }};Copy the code
  • Write the size and isEmpty methods

The implementation of both methods is very simple, I believe that everyone can, I will directly on the code:

// Obtain the number of map key-value pairs var size =function() {  
         returnthis.arr.length; }; // check whether map isEmpty var isEmpty =function() {  
         return this.arr.length <= 0;  
        };  
Copy the code

4. Verification and summary

  • validation

The best proof of a method is that it is written correctly, and I’ll attach all the code below

    function Map(){  
        var struct = function(key, value) { this.key = key; this.value = value; }; // Add map key-value pair varset = function(key, value){  
          for (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
           this.arr[i].value = value;  
           return; }}; this.arr[this.arr.length] = new struct(key, value); }; Var get =function(key) {  
         for (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
           returnthis.arr[i].value; }}returnnull; }; Var remove = var remove =function(key) {  
         var v;  
         for (var i = 0; i < this.arr.length; i++) {  
          v = this.arr.pop();  
          if ( v.key === key ) {  
           continue; } this.arr.unshift(v); }}; // Obtain the number of map key-value pairs var size =function() {  
         returnthis.arr.length; }; // check whether map isEmpty var isEmpty =function() {  
         return this.arr.length <= 0;  
        };  
        this.arr = new Array();  
        this.get = get;  
        this.set = set;  
        this.remove = remove;  
        this.size = size;  
        this.isEmpty = isEmpty;  
       }

       var map=new Map();  
       map.set("xxyang", 100); map.set("xxyang", 90); map.set("xp"."dz");
       console.log(map.get('xxyang')); //90 console.log(map.get('xp')); //dz console.log(map.size()); //2 map.remove("xxyang"); console.log(map.size()); //1 console.log(map.get("xxyang")); //nullCopy the code

Run with vscode to get the following result:

Map

  • conclusion
  1. Map keys can be any value, including functions, objects, and primitive types.
  2. The key values in a Map are ordered, so when traversing it, the Map returns the key values in the order they were inserted.
  3. Map can be iterated directly
  4. Map has some performance advantages in scenarios involving frequent addition and deletion of key-value pairs.
  5. For small white, pick a simple way to implement the source code, is really a good choice, can break the fear of the heart, if you have this fear, go to try. Handwritten source, interview often test, although there are many big guy, also published the relevant article, but the back of the chair is not remember, or to write.

The end of the

Congratulations on reading this article, if there is a mistake, please point it out to me! Feel good, to a 👍 to encourage, ha ha

Refer to the article

  • Map (from MDN Web Docs)