“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

ES6 Set and Map data structures

A list,

ES6 standard provides two new data structures, namely Set and Map, which can also be called Set and dictionary, and weakSet and weakMap correspond to them. This article focuses on introducing these two data structures.

Second, the Set

define

The Set object allows you to store a unique value of any type, either a primitive value or an object reference.

Features:

  1. The Set isThe value of the collection
  2. Values can beAny type
  3. The elements in the Set areThe onlythe

Properties and methods

// The default constructor is Set
Set.prototype.constructor
// Returns the total number of members of the Set instance
Set.prototype.size

// Set instance methods fall into two broad categories: operation methods (for manipulating data) and traversal methods (for traversing members). The following four operations are introduced.

// Do the following

// Add some value, return the Set structure itself
Set.prototype.add(value)

// Delete a value, return a Boolean value indicating whether the deletion was successful
Set.prototype.delete(value)

// Returns a Boolean value indicating whether the value is a member of Set
Set.prototype.has(value)

// Clears all members with no return value
Set.prototype.clear()

// the traversal method

// Returns the traversal of the key name
Set.prototype.keys()

// Returns a traversal of key values
Set.prototype.values()

// Returns the traversal of key and value pairs
Set.prototype.entries()

// Use the callback function to iterate over each member
Set.prototype.forEach()
Copy the code

features

  1. The constructor of a Set must take an iterable or null (undefined).

The argument can be an array, a class array, a string, or any other data type that deploys the Iterator interface

  1. So the uniqueness of the Set element, that’s where the equality check comes in.
  • +0 (+0 is strictly equal to -0) and -0 are different values, but are combined to 0 in Set
  • Multiple nans,undefined, and null will be merged into one
  • Multiple undefined variables can be merged into one
  • Multiple {} will not be merged

  1. Set.prototype.add(value) returns the Set structure itself, so it can be chained.

  1. Set and array interchangeably
// Array => Set
// new Set(arr)
let set = new Set([1.2.3])

// Set => Array
// Array.from(set)
// [...Set]
let arr = Array.from(set)
let arr = [...set]
Copy the code

  1. Array de-duplication (Set version)
let x = [...new Set(numbers)]
Copy the code
  1. The size attribute of Set is writable, but does not take effect.

This is separated from the length of the array

Third, the Map

define

Map data structures, like objects, are collections of key-value pairs, but the range of “keys” is not limited to strings and symbols. Values of all types (including objects) can be used as keys. The Map structure provides value-value mapping and is a more complete Hash structure implementation.

Features:

  1. Save key-value pairs
  2. Value – Value mapping is provided
  3. Traversal follows the original insertion order of the keys

Properties and methods

// 'size' is an accessible attribute that returns the number of Map object members
Map.prototype.size

// Add or update a (new) key-value pair with a specified key and value, returning a Map object
Map.prototype.set(key, value)

// Returns the value of a Map object associated with the specified key, or undefined if the key cannot be found
Map.prototype.get(key)

// If the element exists in the 'Map' object, remove it and return * 'true' *; Otherwise return 'false' if the element does not exist
Map.prototype.delete(key)

// Returns a bool indicating whether the specified element exists in the map
Map.prototype.has(key)

// Remove all elements in the Map object, return undefined
Map.prototype.clear()

// Return a referenced Iterator. It contains the key values for inserting each element in the 'Map' object in sequence
Map.prototype.keys()

// Return a new Iterator. It contains values that are inserted sequentially for each element in the Map object.
Map.prototype.values()

// Return a new 'Iterator' containing '[key, value]' pairs in the same order as the 'Map' objects were inserted
Map.prototype.entries()

// Execute the given function once for each key/value pair in 'Map' in the insertion order
Map.prototype.forEach()
Copy the code

features

  1. Objects and maps comparison
To compare Map Object
The accident of key MapBy default, there are no keys. Contains only explicitly inserted keys. aObjectThere is a prototype, and the key name on the prototype chain may conflict with the key name you set on the object yourself.Note:Although the ES5 works at firstObject.create(null)To create an object without a prototype, but this is not very common.
The type of the key aMapSigma could be PIAny value, including functions, objects, or any primitive type. aObjectTheta has to be a keyStringorSymbol.
The order of the keys MapKey is ordered in. So, when you iterate, oneMapObject returns key values in the order they are inserted. aObjectThe key is unordered note: objects since the ECMAScript 2015 specificationindeedPreserves the creation order of the string and Symbol key; Therefore, iterating over an object with only string keys produces keys in insertion order.
Size  MapThe number of key-value pairs can be easily passedsizeProperties for ObjectThe number of key-value pairs can only be calculated manually
The iteration Map 是 可迭代, so it can be iterated directly. One iterationObjectYou need to get its keys somehow before you can iterate.
performance This is better when key pairs are frequently added or deleted. Optimizations are not made in cases where key/value pairs are frequently added and removed.
  1. In the MapKey equality
  • The key comparison is based onsameValueZeroAlgorithm:
  • NaNIs with theNaNBe equal (thoughNaN ! == NaN), and all other values are based on= = =Operator to determine whether the result is equal.
  • In the current ECMAScript specification,0and+ 0Is considered equal.
  1. The Map size attribute is writable but does not take effect.

This is separated from the length of the array

  1. Map and array relationship

Two-dimensional key-value arrays can be converted to and from Map objects

let kvArray = [["key1"."value1"], ["key2"."value2"]].// Array of two-dimensional key-value pairs => Map object
let myMap = new Map(kvArray);

// Map object => two-dimensional key-value pair array
// Expand the operator using the array. from function

let x0 = Array.from(myMap);

let x1 = [...myMap];

// Or use array. from on key or value iterators to get an Array containing only keys or values
console.log(Array.from(myMap.keys())); // output ["key1", "key2"]

Copy the code
  1. Merge Map objects

New Map([…first,…second]) overwrites the previous Map if there are duplicate keys

let first = new Map([[1.'one'],
  [2.'two'],
  [3.'three']]);let second = new Map([[1.'uno'],
  [2.'dos']]);// When two maps are merged, if there are duplicate keys, the latter overwrites the former.
// The expansion operator essentially converts a Map object into an array.
let merged = new Map([...first, ...second]);
Copy the code
  1. Copy Map objects