preface

This blog is mainly about set and MAP data structures, but I will introduce some examples of deconstructing assignment syntax in the first part of the blog, to ease the discomfort of looking at data structure examples of deconstructing assignment syntax.

Deconstruction assignment

Because deconstruction assignment is used in a variety of different ways and in many cases we don’t know exactly what it does, and even after three days of learning the grammar, we still can’t remember it. So here are some common scenarios for your reference

Swap the values of variables

The traditional way

let x = 1
let y = 2
let z
z = x
x = y
y = z
Copy the code

ES6

let x =1
let y =2
[x,y]=[y,x]
x / / 2
y / / 1
Copy the code

Using this method, it’s much cleaner and much easier to read

Function returns multiple values

function example(){
   return [1.2.3]}let [x,y,z]=example()
Copy the code

The React tutorial uses this method to accept state data

function example(){
	return {x:1.y:2}}let {x,y}=example()
Copy the code

To use this method, you need to correspond to the attributes of the returned object, or it will fail

let [z,y]=example()
z // undefined
y / / 2
Copy the code

Function parameter definition

function fn({x,y}){
     console.log(x,y)
}
fn({x:1.y:2}) / / 1. 2
Copy the code

If you don’t understand the above way can be regarded as the following way

function fn(obj){
   let {x,y}=obj;
    console.log(x,y)
}
fn({x:1.y:2})
Copy the code

I just delete obj and put {x,y} up there.

The same is true for arrays

function fn([x,y,z]){}
fn([1.2.3])
Copy the code

Extracting JSON data

Deconstructing assignments is especially useful for extracting JSON data

let jsonData = {
  id: 42.status: "OK".data: [867.5309]};let { id, status, data: number } = jsonData;
console.log(id,status,number)
/ / or
let {id, status, data}=jsonData;
console.log(id,status,data)
Copy the code

The result is always the same

Map attribute traversal

const map = new Map(a); map.set('first'.'hello');
map.set('second'.'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
Copy the code

If you just want to iterate over the value and not the key, you can write it like this

for(let [,value] of map){}
Copy the code

Module export function

const {useState,useEffect} from 'react'
Copy the code

可迭代

xxxx

Set

A Set is a new data deconstruction for ES6 that is similar to an array except that it does not have duplicate values.

Generate Set data deconstruction

Set itself is a constructor, so we need to generate a Set data deconstruction using new

Parameters to generate

const set=new Set([1.2.3.4.5])
set //Set(5) {1, 2, 3, 4, 5}
Copy the code

Passing an array can generate a Set deconstruction. In fact, arrays are not possible. Any data with an Iterable interface can generate a Set in this way.

Prototype method generation generation

Set data deconstruction can also be generated using the set.prototype. add method

const s= new Set(a)for(let v of [1.2.3.1.2.3]){
	s.add(v)
}
// Set(3) {1, 2, 3}
Copy the code

As you can see above, Set does not record duplicate values

An example of an iterable interface array generation

function fn(){
    return new Set(arguments)
}
fn(1.2.3.4.5.6)
// Set(6) {1, 2, 3, 4, 5, 6}

const set=new Set(a)document.querySelectorAll('div').forEach(div= >{set.add(div)})
Copy the code

duplicate removal

const a=[1.2.1.2]
const b=[...new Set(a)]
Copy the code

The above code uses… The expansion operator expands the Set data deconstruction and wraps it with [] to create an array

Or you can use array.from () to convert arrays, depending on your taste

const a=[1.2.1.2]
const b=Array.from(new Set(a))
Copy the code

Strings can also be de-duplicated

const a='123412'
const b=[...new Set(a)].join(' ')
b / / '1, 2, 3, 4'
Copy the code

The above code is used for string de-duplication, because strings also have an iterable interface that can be passed as arguments to the Set constructor

Set instance properties

Set. The prototype. The constructor, the default to the constructor

Set.prototype.size: Returns the total number of members of a Set instance, similar to the length of the array

Set instance method

Operation method

Add: Set. The prototype. The add (value)

Delete: Set. The prototype. The delete (value)

Check: the Set. The prototype. From the (value)

Clear: Set. The prototype. The clear ()

Iterate over the operation method

Set.prototype.keys() : iterator that returns key names

Set.prototype.values() : iterator that returns key values

Set.prototype.entries() : Returns a traverser for key and value pairs

Set.prototype.foreach () : Use the callback function to iterate over each member

Since the keys and values of the Set data structure are the same, the results returned by keys and values are the same. We can use entries to argue that keys and values are the same

let set= new Set(['qiu'.'yan'.'xi'])
set.forEach((value,key) = >{
	console.log(` value:${value}=>key:${key}`)})/ / value: qiu = > key: qiu
/ / value: yan = > key: yan
/ / value: xi = > key: xi
for(let item of set.entries()){
	console.log(item)
}
//['qiu','qiu']
//['yan','yan']
//['xi','xi']
Copy the code

In the above code, entries are returned each time with an array of key values.

Application of traversal

Since Set has an iterable interface, you can also use a for of loop.

let set= new Set(['qiu'.'yan'.'xi'])
for(let x of set){
	console.log(x)
}
//qiu
//yan
//xi
Copy the code

Cooperate with… The map or filter operator can be used to implement a set in disguised form

let set=new Set([1.2.3.4.5.6])
new Set([...set].map((value,key) = >{return value*2}))
//Set(6) {2, 4, 6, 8, 10, 12}

new Set([...set].filter((value) = >{
return value>3
}))
//Set(3) {4, 5, 6}
Copy the code

Map

In javascript, object objects exist as key-value pairs, but their keys are all strings. When we want to use hash tables, ES6 maps are more suitable than objects. It breaks the restriction of key-value pairs being strings and provides value-value data structures.

Generate Map data structures

Parameters to generate

Map is also a constructor that generates a data structure by passing in a binary array that forms a pair of values.

let map=new Map([['name'.'qiuyanxi'], ['age'.10]])

//Map(2) {"name" => "qiuyanxi", "age" => 10}
Copy the code

Prototype method generation

The position of the Map key can also be an object. We use the set method to generate the Map data structure (adding members).

let map=new Map().set({name:'qiuyanxi'},'male')
//Map(1) {{name:'qiuyanxi'} => "male "}
Copy the code

In fact, when the Map constructor takes an array as an argument, it actually does the following

let array=[[name,'qiu'],[age,10]]
let map = new Map()
array.forEach(([key,value],index) = >{map.set(key,value)})
//Map(2) {"name" => "qiu", "age" => 10}
Copy the code

In the above code, [key,value] is actually deconstructed and assigned to [name,’qiu’], and then set the map object to add corresponding members.

In fact, an array structure can be a parameter to the Map constructor as long as it holds the Iterable interface and each member is a two-element array.

Map prototype method

Map.prototype.size Returns the total number of members of the Map structure

Map.prototype.set(key, value) Adds a member

The Map. The prototype. The get (key) members

Map.prototype.delete(key) Deletes the member

Map.prototype.has(key) returns a Boolean value indicating whether a key is in the current Map object.

Map.prototype.clear() clears all members

const a = {'name':'qiu'}
const map = new Map()
map.set(a,'yanxi')
map.size / / 1
map.get(a) //'yanxi'
map.delete(a) //true
map.clear() 
// Map(0) {}
Copy the code

If the same key is assigned more than once, the original key is overwritten

const map =new Map()
map.set(1.'123')
map.set(1.'456')
map.get(1) / / '456'
Copy the code

Note that when a key is of object type, it is best to read it or override it by reference rather than by writing

const map=new Map()
map.set({name:"qiu"},'123')
map.set({name:"qiu"},'456')
map.get({name:"qiu"}) //undefined
map//Map(2) {{name:'qiu'} => "123", {name:'qiu'} => "456"}
Copy the code

In the above code, I used the map method to set the key names of {name:’qiu’} as objects respectively, but in fact there is a case of consistent key names without value overwriting, and when get reads, undefined is read. This is because the memory address of the key is different, map does not recognize it as a key, so we should pay attention to. In this case, you need to convert the key name to a reference to the address

const map=new Map(a)const n={name:"qiu"}
map.set(n,'123')
map.set(n,'456')
map.get(n) / / '456'
Copy the code

The Map key is bound to the address. As long as the memory address is different, it is regarded as two different keys.

If the Map’s key is a value of a simple type (number, string, Boolean), the Map will treat the two values as one key as long as they are strictly equal, such as 0 and -0 being one key, and true and the string true being two different keys. Also, undefined and NULL are two different keys. Although NaN is not strictly equal to itself, Map treats it as the same key.

const map=new Map()
map.set(0.'123')
map.set(-0.'456')
map //Map(1) {0 => "456"}
map.set(true.123)
map.set('true'.456)
map.set(null.Awesome!)
map.set(undefined.777)
map.set(NaN.888)
map.set(NaN.999)
map //Map(6) {0 => "456", true => 123, "true" => 456, null => 666, undefined => 777, NaN => 999}
Copy the code

Traversal methods

Keys () returns the traverser of the key name

Map.prototype.values() iterator that returns the value

Map.prototype.entries() returns a traverser for all members

Map.prototype.foreach () traverses all member maps in insertion order

const map=new Map([[1.'true'], [2.'false']])
for(let k of map.keys()){console.log(k)} / / 1. 2

for(let k of map.values()){console.log(k)} // 'true' 'false'

for(let k of map.entries()){console.log(k)} //[1, "true"][2, "false"]

map.forEach((value,key) = >{
	console.log(value+':'+key)
}) // true:1 false:2
Copy the code

Transformation of the Map

Convert to an array

The extension operator can be used to quickly convert a Map to an array. Since a Map does not have a Map method, the filter or Map method can be used together with the extension operator

const map=new Map([[1.'one'],
  [2.'two'],
  [3.'three']])
 const a=new Map([...map].filter(([key,value]) = >{
  	return key>2
  }))
  a //Map(1) {3 => "three"}
Copy the code

Convert to object

If all Map keys are strings, they can be converted to objects losslessly; if they are non-strings, they are converted to strings and then to objects

const map=new Map([[8.'one'],
  [9.'two'],
  [10.'three']])
  const obj={}
map.forEach((value,key) = >{
    obj[key]=value
})
obj //{8: "one", 9: "two", 10: "three"}
Copy the code

The object becomes a Map

Use the object.entries () method to turn objects into binary arrays containing key names and values, and then into maps

// Add the above code
let o =Object.entries(obj) 
// [[8, 'one'],[9, 'two'],[10, 'three']]
let map =new Map(o)
Copy the code

The Map into a JSON

We need to convert it to a different JSON object depending on the situation

When the key names are all strings, it can be converted to the object JSON

const map=new Map()
map.set('qiu'.'yanxi')
map.set('height'.'180')
function mapToString(map){
	const obj=Object.create(null)
    map.forEach((value,key) = >{
    obj[key]=value
    })
    return obj
}
const obj=mapToString(map)
JSON.stringify(obj) //"{"qiu":"yanxi","height":"180"}"
Copy the code

When the key name is not just a string, it can be converted to an array JSON

const map=new Map()
map.set([1.2.3].'yanxi')
map.set(['height'].'180')
JSON.stringify([...map])
/ / "[[[1, 2, 3]," yanxi "], [[] "height", "180"]]"
Copy the code

Reference documentation

Wangdoc.com/es6/set-map…