“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

Map object methods

The Map:

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 = ['Michael'.'Bob'.'Tracy'];
var scores = [95.75.85];
Copy the code

To find scores from scores given a name, locate scores from names and retrieve scores from scores. The longer the Array, the longer the time it takes.

If the Map implementation, only need a “name” – “score” comparison table, directly according to the name of the search results, no matter how large the table, the search speed will not be slower. Write a Map in JavaScript as follows:

var m = new Map([['Michael'.95], ['Bob'.75], ['Tracy'.85]]);
m.get('Michael'); / / 95
Copy the code

Initializing a Map requires either a two-dimensional array or an empty Map. Map has the following methods:

var m = new Map(a);// 空Map
m.set('Adam'.67); // Add a new key-value
m.set('Bob'.59);
m.has('Adam'); // Whether key 'Adam' exists: true
m.get('Adam'); / / 67
m.delete('Adam'); // delete key 'Adam'
m.get('Adam'); // undefined
Copy the code

If you add a value to a key multiple times, the subsequent value will flush out the previous value:

var m = new Map(a); m.set('Adam'.67);
m.set('Adam'.88);
m.get('Adam'); / / 88
Copy the code
  • Set:

A Set, like a Map, is a Set of keys but does not store values. Because the key cannot be repeated, there is no duplicate key in Set.

To create a Set, either supply an Array as input, or create an empty Set:

var s1 = new Set(a);/ / null Set
var s2 = new Set([1.2.3]); // contains 1, 2, 3
Copy the code

Duplicate elements are automatically filtered in Set:

var s = new Set([1.2.3.3.'3']);
s; // Set {1, 2, 3, "3"}
Copy the code

Note that the number 3 and the string ‘3’ are different elements.

We can add elements to a Set using the add(key) method, which can be added repeatedly but has no effect:

s.add(4);
s; // Set {1, 2, 3, 4}
s.add(4);
s; Set {1, 2, 3, 4}
Copy the code

The delete(key) method deletes elements:

var s = new Set([1.2.3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}
Copy the code

summary

Map and Set are new data types added in ES6 standards. Determine whether to use them based on the browser support

Definition: a set of key/value pairs.

  • MapObj = new Map()

Note: The keys and values in the collection can be of any type. If you add a value to the collection using an existing key, the new value replaces the old value.

Properties: The following table lists the properties and descriptions of the Map object.

The constructor specifies the function that creates the map. Prototype - The Prototype returns a reference to the Prototype for the map. Size returns the number of elements in the map.Copy the code

Methods: The following table lists the methods and descriptions of the Map object.

Clear removes all elements from the map. Delete removes the specified element from the map. ForEach performs the specified operation on each element in the map. Get returns the specified element in the map. Has Returns true if the map contains the specified element. Set adds a new element to the map. ToString returns a string representation of the mapping. ValueOf returns the original valueOf the specified object. The following example shows how to add members to a Map and then retrieve them. var m = new Map(); m.set(1, "black"); m.set(2, "red"); m.set("colors", 2); m.set({x:1}, 3); m.forEach(function (item, key, mapObj) { document.write(item.toString() + "<br />"); }); document.write("<br />"); document.write(m.get(2)); // Output: // black // red // 2 // 3 // // redCopy the code

Introduction to ES6

ES6 Set and Map data structures:

The main applications of sets and maps are array de-duplication and data storage,

A Set is a data structure called a collection, and a Map is a data structure called a dictionary

A collection of

A Set is a Set of unordered and unique (that is, cannot be repeated) items. You can think of a Set as an array with neither repeating elements nor the concept of order. ES6 provides a new data structure Set. It’s like an array, but the values of the members are unique. There are no duplicate values. The Set itself is a constructor that generates the Set data structure

const s = new Set(a); [2.3.5.4.5.2.2].forEach(x= > s.add(x));
 
for (let i of s) {
  console.log(i);   // 2 3 5 4
}
Copy the code

Removes duplicate members of an array

let array = [1.2.1.4.5.3];
[...new Set(array)]     // [1, 2, 4, 5, 3]
Copy the code

Properties and methods of a Set instance

Size: Returns the number of elements in the Set

Add (value) : Adds a new item to the collectiondelete(value) : Removes a value from the collection has(value) : Returns if the value exists in the collectiontrue, otherwise,falseclear(): Keys () : returns an array containing all the keys in the set Values () : Returns an array containing all the values in the set Entries: Returns an array containing all the key/value pairs in the set Used to perform some operation on a collection member, creating a collection with no return valuefunction Set(arr = []) {    // You can pass in an array
    let items = {};
    this.size = 0;  // Record the number of members in the collection
}
 
module.exports = Set;
Copy the code

The {} object is used to represent collections because objects do not allow a key to point to two different attributes, ensuring that the elements in the collection are unique

Next, we need to add some collection manipulation methods, as implemented in ES6 by the Set class

From the way

The first thing to implement is the HAS method, which is called in other methods like Add and DELETE, so let’s look at its implementation

function Set() {
    let items = {};
    this.size = 0;
    
    / / from the (val) method
    this.has = function(val) {
        // Objects have a hasOwnProperty method that determines whether they have a particular property
        return items.hasOwnProperty(val);  
    };
}
Copy the code

The add method

Next, implement the Add method

    / / add (val) method
    this.add = function(val) {
        if (!this.has(val)) {
            items[val] = val;
            this.size++;    // Add the number of collection members
            return true;
        }
        return false;
    };
Copy the code

For a given val, you can detect whether it exists in the collection

If it doesn’t exist, add it to the collection and return true if it does, return false without doing anything

Delete and clear methods

So let’s go ahead and write both this time

    / / delete (val) method
    this.delete = function(val) {
        if (this.has(val)) {
            delete items[val];  // Delete the properties on the Items object
            this.size--;
            return true;
        }
        return false;
    };
    / / clear method
    this.clear = function() {
        items = {};     // Just assign an empty object to the collection
        this.size = 0;
    };
Copy the code

The delete method checks if val exists in the collection and deletes it from the collection, returning true

All of the above is the operation method, let’s implement the traversal method again

Keys, values methods

These two methods can be implemented together, because it is easy to implement the corresponding method through the ES6 extension of Object, let’s see the concrete implementation, above code:

    / / keys () method
    this.keys = function() {
        return Object.keys(items);  // Returns an array of all the key names iterating through the collection
    };
    / / values () method
    this.values = function() {
        return Object.values(items);  // Returns an array of keys iterating through the collection
    };
Copy the code

Let’s use it and see

// set.js
const Set = require('./Set.js');    // Import the written Set class
let set = new Set(a); set.add(1);
set.add(3);
set.add(2);
console.log(set.keys());    // ['1', '2', '3']
console.log(set.values());  // [1, 2, 3]
Copy the code

The Set method is used to iterate over an array in order of size. The Set method is used to iterate over an array in order of size. The Set method is used to iterate over an array in order of size

The forEach method

ForEach = forEach = forEach = forEach = forEach = forEach = forEach = forEach = forEach = forEach = forEach = forEach

ForEach = forEach = forEach = forEach = forEach = forEach

    ForEach (fn, context)
    this.forEach = function(fn, context = this) {
        for (let i = 0; i < this.size; i++) {
            let item = Object.keys(items)[i]; fn.call(context, item, item, items); }};Copy the code

Use the forEach method

// set.js const Set = require('./Set.js'); let set = new Set(); set.add(1); set.add(4); set.add('3'); set.forEach((value, key) => console.log(key + ' : ' + value)); // 1:1, 3:3, 4:4 let arr = set.values(); // [ 1, 3, 4 ] arr = new Set(arr.map(x => x * 2)).values(); console.log(arr); // [2, 6, 8]Copy the code

Basically implement the Set structure method, however, found a problem, that is, every time you add an element to add this is really cumbersome to write, Set can accept an array as a parameter, so let’s implement this

function Set(arr = []) {    // Pass in the accepted array, if not, specify an empty array as the initial value
    let items = {};
    this.size = 0;
    / / from the method
    this.has = function (val) {
        return items.hasOwnProperty(val);
    };
    / / the add method
    this.add = function (val) {
        // If there is no existing items, you can write directly
        if (!this.has(val)) {
            items[val] = val;
            this.size++;
            return true;
        }
        return false;
    };
    arr.forEach((val, i) = > {   // Iterate over the array passed in
        this.add(val);          // Add each item in the array to the collection
    });
    / / to omit...
}
Copy the code

Let’s see if we can now support arrays passed in

// Use map and filter indirectly
const Set = require('./Set.js');
let arr = new Set([1.2.3]).values();
m = new Set(arr.map(x= > x * 2));
f = new Set(arr.filter(x= > x>1));
console.log(m.values());    // [2, 4, 6]
console.log(f.values());    // [2, 3]
 
// Array decrement
let arr2 = new Set([3.5.2.1.2.5.5]).values();
console.log(arr2);  // [1, 2, 3, 5]
Copy the code

We now have an implementation of the Set class that is very similar to ES6. As mentioned earlier, you can also use arrays instead of objects to store elements. For those of you who like to do things, you can try it later

In addition, Set can also implement union, intersection, difference.

We have to do the whole thing, so let’s do it one at a time

Union and INTERSECT

The mathematical concept of union, the union of set A and B, is represented by A∪B intersection, and the intersection of set A and B is represented by A∩B

Now let’s implement the union method

    / / and set
    this.union = function (other) {
        let union = new Set(a);let values = this.values();
        for (let i = 0; i < values.length; i++) {
            union.add(values[i]);
        }
        values = other.values();    // Reassign values to the new collection
        for (let i = 0; i < values.length; i++) {
            union.add(values[i]);
        }
 
        return union;
    };
    / / intersection
    this.intersect = function (other) {
        let intersect = new Set(a);let values = this.values();
        for (let i = 0; i < values.length; i++) {
            if (other.has(values[i])) {     // Check whether it also exists in other
                intersect.add(values[i]);   // If there is one, it is like adding elements to intersect}}return intersect;
    };
Copy the code

Let’s see how the difference sets are implemented, and then let’s test them together

Difference difference set

The mathematical concept of the difference set, the difference set of A and B, is represented as A minus B

    / / difference set
    this.difference = function (other) {
        let difference = new Set(a);let values = this.values();
        for (let i = 0; i < values.length; i++) {
            if(! other.has(values[i])) {// Add to the new collection that does not exist in the other collectiondifference.add(values[i]); }}return difference;
    };
Copy the code
  • Full implementation of Set

In this, first to you stick a complete implementation code

function Set(arr = []) { let items = {}; this.size = 0; This. Has = function (val) {return items. HasOwnProperty (val); }; This. add = function (val) {// If (! this.has(val)) { items[val] = val; this.size++; return true; } return false; }; arr.forEach((val, i) => { this.add(val); }); This. delete = function (val) {if (this.has(val)) {delete items[val]; // Delete the items property this.size--; return true; } return false; }; This. Clear = function () {items = {}; this.size = 0; }; This. Keys = function () {return object.keys (items); }; // values method this.values = function () {return object.values (items); ForEach = function (fn, context = this) {for (let I = 0; i < this.size; i++) { let item = Object.keys(items)[i]; fn.call(context, item, item, items); }} this.union = function (other) {let union = new Set(); let values = this.values(); for (let i = 0; i < values.length; i++) { union.add(values[i]); } values = other.values(); For (let I = 0; i < values.length; i++) { union.add(values[i]); } return union; }; // intersection this.intersect = function (other) {let intersect = new Set(); let values = this.values(); for (let i = 0; i < values.length; i++) { if (other.has(values[i])) { intersect.add(values[i]); } } return intersect; }; // this. Difference = function (other) {let difference = new Set(); let values = this.values(); for (let i = 0; i < values.length; i++) { if (! other.has(values[i])) { difference.add(values[i]); } } return difference; }; Subset = function(other) {if (this.size > other.size) {return false; } else { let values = this.values(); for (let i = 0; i < values.length; i++) { console.log(values[i]) console.log(other.values()) if (! other.has(values[i])) { return false; } } return true; }}; } module.exports = Set;Copy the code

Let’s test it out

const Set = require('./Set.js'); let set = new Set([2, 1, 3]); console.log(set.keys()); // [ '1', '2', '3' ] console.log(set.values()); // [ 1, 2, 3 ] console.log(set.size); // 3 set.delete(1); console.log(set.values()); // [ 2, 3 ] set.clear(); console.log(set.size); // let a = [1, 2, 3]; let b = new Set([4, 3, 2]); let union = new Set(a).union(b).values(); console.log(union); / / [1, 2, 3, 4] / / intersection let c = new Set ([4, 3, 2)); Let intersect = new Set([1,2,3]).intersect(c).values(); console.log(intersect); // [2, 3] // let d = new Set([4, 3, 2]); Let difference = new Set([1,2,3]).difference(d).values(); // the difference set between [1,2,3] and [4,3,2] is 1 console.log(difference); / / [1]Copy the code

So far we use the Set data structure to achieve similar to ES6 Set class, the above use method is also basically the same, you can later have time to start to knock knock take a look, can not miss passing through

Now that we have completed the implementation of Set, we need to write the Map in pairs

The dictionary

Another structure in the data structure is called a dictionary, which implements the Map class based on ES6

So what’s the difference between a set and a dictionary?

Common: Collections and dictionaries can store values that are not duplicated

Differences: Collections store elements in the form of [value, value], while dictionaries store elements in the form of [key, value]. Therefore, it is clear that Map is also used to store data. Compared with Object, Map only provides “string-value” mapping, Map provides “value-value” mapping. That is, if you need key-value data structures, Map is better than Object

Here’s a look at the basics:

const m = new Map();
const o = {p: 'Hello World'};
m.set(o, 'content')
m.get(o) // "content"
 
m.has(o) // true
m.delete(o) // true
m.has(o) // false
Copy the code

This is the basic use of Map, and more useful methods will be shown later as the implementation progresses

  • Map properties and methods

Properties:

  • Size: Returns the number of elements contained in the dictionary

Operation method:

Set (key, val): adds a new element to the dictionary GET (key): finds a specific value by key value and returns has(key): returns true if the key exists in the dictionary, false otherwise delete(key): Clear (): removes all elements from the dictionary. Traversal method: keys(): returns all keys in the dictionary as an array. Values (): returns all values in the dictionary as an array. Function Map() {let items = {}; function Map() {let items = {}; } module.exports = Map; / / exportCopy the code

Now that you’ve created the skeleton of a dictionary, start adding some methods

  • From the way

The first is of course has, because it’s used in both set and get, and the implementation is very similar to the set I wrote earlier

function Map() {
    let items = {};
    / / from the (key) method
    this.has = function(val) {
        return items.hasOwnProperty(val);
    };
}
Copy the code

Once we have implemented the HAS method, we can determine whether the dictionary contains the property and proceed to implement other methods

  • Set and get methods
Set (key, val); // Set (key, val);  new Map().set({}, 'a') this.set = function(key, val) { items[key] = val; }; This. get = function(key) {// If an unknown key is read, undefined return this.has(key)? items[key] : undefined; }; Copy the set and get methods, then delete and clear methods, no nonsense, This. delete = function(key) {if (this.has(key)) {// Delete items[key]; // Delete the items attribute this.size--; Return true; } return false; }; // clear() this.clear = function() {items = {}; this.size = 0; }; Keys = function() {return object.keys (items); }; // values() method this.values = function() {return object.values (items); }; ForEach = function(fn, context = this) {for (let I = 0; i < this.size; i++) { let key = Object.keys(items)[i]; let value = Object.values(items)[i]; fn.call(context, value, key, items); }};Copy the code

Map complete implementation

function Map() {
    let items = {};
    this.size = 0;
 
    // Do the following
    / / from the method
    this.has = function(val) {
        return items.hasOwnProperty(val);
    };
    // set(key, val)
    this.set = function(key, val) {
        items[key] = val;
        this.size++;
    };
    / / get (key) method
    this.get = function(key) {
        return this.has(key) ? items[key] : undefined;
    };
    / / delete (key) method
    this.delete = function(key) {
        if (this.has(key)) {
            delete items[key];
            this.size--;
            return true;
        }
        return false;
    };
    / / the clear () method
    this.clear = function() {
        items = {};
        this.size = 0;
    };
    // the traversal method
    / / keys () method
    this.keys = function() {
        return Object.keys(items);
    };
    / / values () method
    this.values = function() {
        return Object.values(items);
    };
    ForEach (fn, context)
    this.forEach = function(fn, context = this) {
        for (let i = 0; i < this.size; i++) {
            let key = Object.keys(items)[i];
            let value = Object.values(items)[i]; fn.call(context, value, key, items); }}; }module.exports = Map;
Copy the code

Take a look at the following test chestnut

    // map.js
    // Use the Map class
    const Map = require('./Map.js');
    let m = new Map(a); m.set('Jay'.'the Jay Chou');
    m.set(true.'really');
    console.log(m.has('Chou'));  // false
    console.log(m.size);        / / 2
    console.log(m.keys());      // [ 'Jay', 'true' ]
    console.log(m.values());    // [ 'Jay的Chou', '真的' ]
    console.log(m.get('jay'));  // undefined
    
    m.delete(true);
    console.log(m.keys());      // [ 'Jay' ]
    console.log(m.values());    // ['Jay Chou']
Copy the code

ES6 adds a function called from to Array to convert other objects into arrays.

Of course, there are requirements for other objects, but not all of them. You can convert both types of objects into arrays.

1. Objects with the Iterator interface deployed, such as Set, Map, and Array.

2. Array-like objects, what is an array object, is that an object must have the length attribute, without length, the output is empty array.

  • Convert the map

Converts the Map object’s key-value pair to a one-dimensional array.

The sequence of conversion of array element is actually key1, value1, value2, key2, key3, value3…

const map1 = new Map(a); map1.set('k1'.1);
map1.set('k2'.2);
map1.set('k3'.3);
console.log('%s'.Array. From (map1)) results: k1,1,k2,2,k3,3
Copy the code
  • Convert the set

Converts the elements of a Set object to an array.

const set1 = new Set(a); set1.add(1).add(2).add(3)
console.log('%s'.ArrayResults. The from (characters))1.2.3
Copy the code
  • Conversion string

You can split ASCII strings into a single piece of data, and you can exactly split Unicode strings into arrays.

Console. log('%s', array. from('hello world')) console.log('%s', array. from('\ U767d \u8272\u7684\u6d77')) result: H e L L O W O R L D white seaCopy the code
  • Array like object

An array-like object must have length, and their element attribute names must be numeric values or characters that can be converted to numeric values.

Note: The attribute name represents the index number of the array. Without this index number, the corresponding element in the resulting array is empty.

The console. The log (' % s', Array. The from ({0: '0', 1, '1', 3: '3', length: 4})) results: 0, 1, and 3Copy the code

If the object does not have length, then the output is an empty array.

Console. log('%s', array. from({0: 0, 1: 1}))) results in an empty Array. When the property name of an object cannot be converted to an index number. console.log('%s', Array.from({ a: '1', b: Array.from(arrayLike[, mapFn[, thisArg]]) arrayLike: converted object. MapFn: map function. ThisArg: the object to which this points in the map function. The second parameter, the map function, is used to process each element in the transformation and use the processed result as the element value of the result array. Console. log('%s', array. from([1, 2, 3, 4, 5], (n) => n + 1)) 2,3,4,5,6 the third parameter, the object referred to by this in the map function, is very useful. We can separate the data to be processed from the object, and encapsulate different methods of processing data into different objects with the same name. When array. from is called to transform data objects, different processing objects can be injected as needed to get different results, suitable for decoupling. This approach is an application of the template design pattern, somewhat similar to dependency injection. let diObj = { handle: function(n){ return n + 2 } } console.log('%s', Array.from( [1, 2, 3, 4, 5], function (x){ return this.handle(x) }, DiObj) results: 3,4,5,6,7Copy the code