Symbol

  • ES6 introduces a new primitive data typeSymbolRepresents a unique value. It is the seventh data type of the JavaScript language, the first six being:undefined,null, Boolean, String, Number, Object.

The Symbol value is generated by the Symbol function.

let s = Symbol(a);typeof s
// "symbol"
Copy the code

Note that the new command cannot be used before the Symbol function, otherwise an error will be reported. This is because the generated Symbol is a primitive type value, not an object. That is, because the Symbol value is not an object, attributes cannot be added. Basically, it’s a data type similar to a string.

The Symbol function can take a string as an argument representing a description of the Symbol instance, mainly to make it easier to distinguish when displayed on the console or converted to a string.

let s1 = Symbol('foo');
let s2 = Symbol('bar');

s1 // Symbol(foo)
s2 // Symbol(bar)

s1.toString() // "Symbol(foo)"
s2.toString() // "Symbol(bar)"
Copy the code

Note that the parameter to the Symbol function only represents a description of the current Symbol value, so the return value of the Symbol function with the same parameter is not equal.

// No arguments
let s1 = Symbol(a);let s2 = Symbol(a); s1 === s2// false

// With parameters
let s1 = Symbol('foo');
let s2 = Symbol('foo');

s1 === s2 // false
Copy the code

ES2019 provides an instance attribute, Description, that returns the description of Symbol directly.

const sym = Symbol('foo');

sym.description // "foo"
Copy the code

Symbol as attribute name

Since each Symbol value is not equal, this means that the Symbol value can be used as an identifier for the property name of the object, ensuring that no property with the same name will appear. This is useful in cases where an object is made up of multiple modules, preventing a key from being accidentally overwritten or overwritten.

let mySymbol = Symbol(a);// The first way
let a = {};
a[mySymbol] = 'Hello! ';
Copy the code

2. Traversal of attribute names

Symbol is the attribute name. When traversing the object, the attribute does not appear in the for… In, for… Of loop, will not be the Object. The keys (), Object, getOwnPropertyNames (), JSON. The stringify () returns.

However, it is not private property, with an Object. The getOwnPropertySymbols () method, which can get all the Symbol of specified Object attribute names. This method returns an array of all the Symbol values used as attribute names for the current object.

const obj = {};
let a = Symbol('a');
let b = Symbol('b');

obj[a] = 'Hello';
obj[b] = 'World';

const objectSymbols = Object.getOwnPropertySymbols(obj);

objectSymbols
// [Symbol(a), Symbol(b)]
Copy the code

Code above is Object. GetOwnPropertySymbols () method of sample, you can get all the Symbol attribute names.

3, the Symbol. The iterator

Object that points to the default traverser method for that object.

const myIterable = {};
myIterable[Symbol.iterator] = function* () {
  yield 1;
  yield 2;
  yield 3;
};

[...myIterable] / / [1, 2, 3]
Copy the code

Set

1, set data structure deduplication

// Remove duplicate members of the array
[...new Set(array)]
Copy the code

The above method can also be used to remove duplicate characters from a string.

[...new Set('ababbc')].join(' ')
// "abc"
Copy the code

Set instance properties and methods

Instances of the Set structure have the following properties.

  • Set.prototype.constructorThe: constructor is the defaultSetFunction.
  • Set.prototype.sizeReturns theSetThe total number of members of an instance.

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

  • Set.prototype.add(value): adds a value and returns the Set structure itself.
  • Set.prototype.delete(value): Deletes a value and returns a Boolean value indicating whether the deletion was successful.
  • Set.prototype.has(value): Returns a Boolean value indicating whether the value isSetA member of.
  • Set.prototype.clear(): Clears all members with no return value.

Examples of these properties and methods are shown below.

s.add(1).add(2).add(2);
// Notice that 2 is added twice

s.size / / 2

s.has(1) // true
s.has(2) // true
s.has(3) // false

s.delete(2);
s.has(2) // false
Copy the code

3. Traversal operation

An instance of a Set structure has four traversal methods that can be used to traverse members.

  • Set.prototype.keys(): returns a traverser for key names
  • Set.prototype.values(): returns a traverser for key values
  • Set.prototype.entries(): returns a traverser for key-value pairs
  • Set.prototype.forEach(): Iterates through each member using the callback function

In particular, the traversal order of a Set is the insertion order. This feature can be useful, such as using Set to hold a list of callback functions that are guaranteed to be called in the order they were added.

The array. from method converts a Set structure to an Array.
    const items = new Set([1.3.4.5.6.6.7.7])
    console.log(items)
    const arr = Array.from(items)
    console.log(arr) / /,3,4,5,7 [1]
    // keys returns kenming
    for (let set of items.keys()) {
      console.log(set); // 1, 3, 4, 5, 6, 7
    }
    // values returns the key value
    for (let set of items.values()) {
      console.log(set); // 1, 3, 4, 5, 6, 7
    }
    The // entries method returns a traverser that contains both the key name and the key value, so it prints an array of identical members one at a time.
    for (let set of items.entries()) {
      console.log(set); // [1, 1] [3, 3] [4, 4] [5, 5] [6, 6] [7, 7]
    }

Copy the code

An instance of a Set structure is traversable by default, and its default traverser generator is its values method.

Set.prototype[Symbol.iterator] === Set.prototype.values
// true
Copy the code

This means that you can omit the values method and use for… Of loops through Set.

//
const item2 = new Set(['a'.'b'.'c'.'d'])
for (const set of item2) {
    console.log(set);
}
Copy the code

Application of traversal

Extended operators (…) Internally use for… Of loop, so it can also be used for Set structures.

let set = new Set(['red'.'green'.'blue']);
let arr = [...set];
// ['red', 'green', 'blue']
Copy the code

The extension operator, combined with the Set structure, removes duplicate members of an array.

let arr = [3.5.2.2.5.5];
let unique = [...new Set(arr)];
/ / [3, 5, 2]
Copy the code

Furthermore, the map and filter methods of arrays can also be used indirectly with sets.

let set = new Set([1.2.3]);
set = new Set([...set].map(x= > x * 2));
{2, 4, 6}

let set = new Set([1.2.3.4.5]);
set = new Set([...set].filter(x= > (x % 2) = =0));
Set {2, 4}
Copy the code

Therefore, it is easy to implement Union, intersection, and Difference using Set.

let a = new Set([1.2.3]);
let b = new Set([4.3.2]);

/ / and set
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

/ / intersection
let intersect = new Set([...a].filter(x= > b.has(x)));
// set {2, 3}

// The difference between a and b
let difference = new Set([...a].filter(x= >! b.has(x)));// Set {1}
Copy the code

Map

1. Basic Usage

ES6 provides Map data structures. It is a collection of key-value pairs similar to objects, but the range of “keys” is not limited to strings. Values of all types (including objects) can be used as keys. In other words, the Object structure provides string-value mapping, and the Map structure provides value-value mapping, which is a more complete Hash structure implementation. If you need key-value data structures, Map is better than Object.

const m = new Map(a); m.set('name'.'Joe')
m.get('name')
console.log(m.get('name')) / / zhang SAN
console.log(m.has('name')) // true
console.log(m.has('age')) // false
console.log(m.delete('name')) // true
console.log(m.has('name')) // false
Copy the code

As a constructor, a Map can also take an array as an argument. The members of this array are arrays representing key-value pairs.

const map = new Map([['name'.'Joe'],
  ['title'.'Author']]); map.size/ / 2
map.has('name') // true
map.get('name') // "/"
map.has('title') // true
map.get('title') // "Author"
Copy the code

Returns undefined if an unknown key is read.

new Map().get('asfddfsasadf')
// undefined
Copy the code

Note that only references to the same object are treated as the same key by the Map structure. Be very careful about this.

const map = new Map(a); map.set(['a'].555);
map.get(['a']) // undefined
Copy the code

The set and GET methods in the above code appear to be for the same key, but in fact they are two different array instances, the memory address is different, so the get method cannot read the key, return undefined.

Similarly, two instances of the same value are treated as two keys in the Map structure.

const map = new Map(a);const k1 = ['a'];
const k2 = ['a'];

map
.set(k1, 111)
.set(k2, 222);

map.get(k1) / / 111
map.get(k2) / / 222
Copy the code

2. Instance properties and operation methods

(1) Size attribute

The size property returns the total number of Map structure members.

const map = new Map(a); map.set('foo'.true);
map.set('bar'.false);

map.size / / 2
Copy the code

Prototype set(key, value)

The set method sets the key corresponding to the key name key to value and returns the entire Map structure. If the key already has a value, the key value is updated, otherwise the key is generated.

const m = new Map(a); m.set('edition'.6)        // keys are strings
m.set(262.'standard')     // Keys are numeric values
m.set(undefined.'nah')    / / key is undefined
Copy the code

The set method returns the current Map object, so it can be chained.

let map = new Map()
  .set(1.'a')
  .set(2.'b')
  .set(3.'c');
Copy the code

(3) the Map. The prototype. The get (key)

The get method reads the corresponding key, and returns undefined if the key is not found.

const m = new Map(a);const hello = function() {console.log('hello'); }; m.set(hello,'Hello ES6! ') // Keys are functions

m.get(hello)  // Hello ES6!
Copy the code

(4) the Map) prototype) from the (key)

The HAS method returns a Boolean value indicating whether a key is in the current Map object.

const m = new Map(a); m.set('edition'.6);
m.set(262.'standard');
m.set(undefined.'nah');

m.has('edition')     // true
m.has('years')       // false
m.has(262)           // true
m.has(undefined)     // true
Copy the code

(5) the Map. The prototype. The delete (key)

The delete method deletes a key and returns true. If deletion fails, return false.

const m = new Map(a); m.set(undefined.'nah');
m.has(undefined)     // true

m.delete(undefined)
m.has(undefined)       // false
Copy the code

(6) the Map. The prototype. The clear ()

The clear method clears all members with no return value.

let map = new Map(a); map.set('foo'.true);
map.set('bar'.false);

map.size / / 2
map.clear()
map.size / / 0
Copy the code

(1) Size attribute

The size property returns the total number of Map structure members.

const map = new Map(a); map.set('foo'.true);
map.set('bar'.false);

map.size / / 2
Copy the code

Prototype set(key, value)

The set method sets the key corresponding to the key name key to value and returns the entire Map structure. If the key already has a value, the key value is updated, otherwise the key is generated.

const m = new Map(a); m.set('edition'.6)        // keys are strings
m.set(262.'standard')     // Keys are numeric values
m.set(undefined.'nah')    / / key is undefined
Copy the code

The set method returns the current Map object, so it can be chained.

let map = new Map()
  .set(1.'a')
  .set(2.'b')
  .set(3.'c');
Copy the code

(3) the Map. The prototype. The get (key)

The get method reads the corresponding key, and returns undefined if the key is not found.

const m = new Map(a);const hello = function() {console.log('hello'); }; m.set(hello,'Hello ES6! ') // Keys are functions

m.get(hello)  // Hello ES6!
Copy the code

(4) the Map) prototype) from the (key)

The HAS method returns a Boolean value indicating whether a key is in the current Map object.

const m = new Map(a); m.set('edition'.6);
m.set(262.'standard');
m.set(undefined.'nah');

m.has('edition')     // true
m.has('years')       // false
m.has(262)           // true
m.has(undefined)     // true
Copy the code

(5) the Map. The prototype. The delete (key)

The delete method deletes a key and returns true. If deletion fails, return false.

const m = new Map(a); m.set(undefined.'nah');
m.has(undefined)     // true

m.delete(undefined)
m.has(undefined)       // false
Copy the code

(6) the Map. The prototype. The clear ()

The clear method clears all members with no return value.

let map = new Map(a); map.set('foo'.true);
map.set('bar'.false);

map.size / / 2
map.clear()
map.size / / 0
Copy the code

(1) Size attribute

The size property returns the total number of Map structure members.

const map = new Map(a); map.set('foo'.true);
map.set('bar'.false);

map.size / / 2
Copy the code

Prototype set(key, value)

The set method sets the key corresponding to the key name key to value and returns the entire Map structure. If the key already has a value, the key value is updated, otherwise the key is generated.

const m = new Map(a); m.set('edition'.6)        // keys are strings
m.set(262.'standard')     // Keys are numeric values
m.set(undefined.'nah')    / / key is undefined
Copy the code

The set method returns the current Map object, so it can be chained.

let map = new Map()
  .set(1.'a')
  .set(2.'b')
  .set(3.'c');
Copy the code

(3) the Map. The prototype. The get (key)

The get method reads the corresponding key, and returns undefined if the key is not found.

const m = new Map(a);const hello = function() {console.log('hello'); }; m.set(hello,'Hello ES6! ') // Keys are functions

m.get(hello)  // Hello ES6!
Copy the code

(4) the Map) prototype) from the (key)

The HAS method returns a Boolean value indicating whether a key is in the current Map object.

const m = new Map(a); m.set('edition'.6);
m.set(262.'standard');
m.set(undefined.'nah');

m.has('edition')     // true
m.has('years')       // false
m.has(262)           // true
m.has(undefined)     // true
Copy the code

(5) the Map. The prototype. The delete (key)

The delete method deletes a key and returns true. If deletion fails, return false.

const m = new Map(a); m.set(undefined.'nah');
m.has(undefined)     // true

m.delete(undefined)
m.has(undefined)       // false
Copy the code

(6) the Map. The prototype. The clear ()

The clear method clears all members with no return value.

let map = new Map(a); map.set('foo'.true);
map.set('bar'.false);

map.size / / 2
map.clear()
map.size / / 0
Copy the code

3. Traversal method

The Map structure natively provides three traverser generating functions and one traversal method.

  • Map.prototype.keys(): returns a traverser for key names.
  • Map.prototype.values(): returns a traverser for key values.
  • Map.prototype.entries(): returns a traverser for all members.
  • Map.prototype.forEach(): Traverses all Map members.

Note in particular that the Map traversal order is the insertion order.

// the traversal method
    const m2 = new Map()
      .set('a'.1)
      .set('b'.2)
      .set('c'.3)
    for (const item of m2.keys()) {
      console.log(item) // a,b,c
    }
    for (const item of m2.values()) {
      console.log(item) / / 1, 2, 3
    }
    for (const item of m2.entries()) {
      console.log(item) // ["a", 1]["b", 2] ["c", 3]
    }
Copy the code

A faster way to convert a Map structure into an array structure is to use the extension operator (…). .

const map = new Map([[1.'one'],
  [2.'two'],
  [3.'three']]); [...map.keys()]/ / [1, 2, 3]

[...map.values()]
// ['one', 'two', 'three']

[...map.entries()]
// [[1,'one'], [2, 'two'], [3, 'three']]

[...map]
// [[1,'one'], [2, 'two'], [3, 'three']]
Copy the code

4. Interconversion with other data structures

(1) Map is converted into an array

As mentioned earlier, the most convenient way to turn a Map into an array is to use the extension operator (…). .

const myMap = new Map()
  .set(true.7)
  .set({foo: 3},'abc']);
[...myMap]
// [ [ true, 7 ], [ { foo: 3 }, [ 'abc' ] ] ]
Copy the code

(2) The array is converted to Map

The array is converted to a Map by passing it to the Map constructor.

new Map([[true.7],
  [{foo: 3},'abc']]])// Map {
// true => 7,
// Object {foo: 3} => ['abc']
// }
Copy the code

(3) Map is converted into an object

If all Map keys are strings, it can be converted to objects losslessly.

function strMapToObj(strMap) {
  let obj = Object.create(null);
  for (let [k,v] of strMap) {
    obj[k] = v;
  }
  return obj;
}

const myMap = new Map()
  .set('yes'.true)
  .set('no'.false);
strMapToObj(myMap)
// { yes: true, no: false }
Copy the code

If there is a non-string key name, it is converted to a string and used as the object’s key name.

(4) The object is converted to Map

Objects can be turned into maps through Object.entries().

let obj = {"a":1."b":2};
let map = new Map(Object.entries(obj));
Copy the code