When I was learning ES6, I had no idea of the application scenarios of Set and Map, but thought they were mostly used for array de-duplication and data storage. Later, I gradually realized that Set is a data structure called collection and Map is a data structure called dictionary.
This article is included in gitthub: github.com/Michael-lzg…
Set
The Set itself is a constructor used to generate the Set data structure. The Set function can take an array (or some other data structure with an Iterable interface) as an argument for initialization. The Set object allows you to store any type of value, whether primitive or object reference. It is similar to an array, but the values of the members are unique and there are no duplicate values.
const s = new Set(to)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
Special values in Set
A Set object stores a value that is always unique, so you need to determine whether two values are identical. There are several special values that require special treatment:
- +0 and -0 are identical in the sense that they store uniqueness, so they are not repeated
undefined
与undefined
It’s identical, so it doesn’t repeatNaN
与NaN
Is not identical, but inSet
Believe in theNaN
与NaN
Equal. There can only be one of them.
Set attributes:
size
: Returns the number of elements contained in the collection
const items = new Set([1.2.3.4.5.5.5.5])
items.size / / 5
Copy the code
Set instance object method
add(value)
: Adds a value, returnsSet
The structure itself (can be chain-called).delete(value)
: Deletes a value. The system returns if the value is deleted successfullytrue
Otherwise returnfalse
.has(value)
: Returns a Boolean value indicating whether the value isSet
A member of.clear()
: Clears all members with no return value.
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
Traversal methods
keys()
: returns a traverser for key names.values()
: returns a traverser for key values.entries()
: returns a traverser for key-value pairs.forEach()
: Iterates through each member using the callback function.
Because the Set structure has no key name, only the key value (or the key name and the key value are the same value), the keys and values methods behave exactly the same.
let set = new Set(['red'.'green'.'blue'])
for (let item of set.keys()) {
console.log(item)
}
// red
// green
// blue
for (let item of set.values()) {
console.log(item)
}
// red
// green
// blue
for (let item of set.entries()) {
console.log(item)
}
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]
Copy the code
Compare Array with Set
Array
的indexOf
Methods thanSet
的has
Method inefficiencySet
Contains no duplicate values (you can use this feature to deduplicate an array)Set
throughdelete
Method to delete a value, whileArray
Only throughsplice
. The former is more convenient to useArray
A lot of new waysmap
,filter
,some
,every
Is such asSet
None (but the two can be used interchangeably)
The application of the Set
The array. from method converts a Set structure to an Array.
const items = new Set([1.2.3.4.5])
const array = Array.from(items)
Copy the code
2. Array deduplication
// Remove duplicate members of the array; [...newSet(array)]
Array.from(new Set(array))
Copy the code
3. 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
4, implement Union (Union), intersection (Intersect) and difference 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}
/ / difference set
let difference = new Set([...a].filter((x) = >! b.has(x)))// Set {1}
Copy the code
weakSet
WeakSet structure is similar to Set, which is also a collection of non-repeating values.
- Members are arrays and array-like objects if called
add()
Method that passes arguments to non-array and array-like objects, throws an error.
const b = [1.2[1.2]]
new WeakSet(b) // Uncaught TypeError: Invalid value used in weak set
Copy the code
- Members are weak references that can be collected by the garbage collection mechanism and can be used to hold DOM nodes without causing memory leaks.
WeakSet
Is not iterable and therefore cannot be used infor-of
And so on.WeakSet
There is nosize
Properties.
Map
A Map stores key-value pairs in the form of key-values. Keys and values can be of any type, that is, objects can also be used as keys. The idea behind maps is that all kinds of values can be used as keys. The Map provides value-value mappings.
The difference between Map and Object
Object
The object has a stereotype, which means it has a defaultkey
The value is above the object unless we use itObject.create(null)
Create an object without a prototype;- in
Object
Object, can only putString
和Symbol
As akey
Value, but inMap
,key
Values can be any base type (String
.Number
.Boolean
.undefined
.NaN
… .). , or object (Map
.Set
.Object
.Function
,Symbol
,null
… .). ; - through
Map
In thesize
Property, which can be easily obtainedMap
Length, to getObject
You can only calculate the length manually
The properties of the Map
- Size: Returns the number of elements contained in the collection
const map = new Map()
map.set('foo', ture)
map.set('bar'.false)
map.size / / 2
Copy the code
Map object method
set(key, val)
To:Map
Add a new element toget(key)
: Finds a specific value by key value and returns ithas(key)
Judge:Map
ObjectKey
The corresponding value is returnedtrue
Otherwise returnfalse
delete(key)
: From by key valueMap
To remove the corresponding dataclear()
: will thisMap
Delete all elements in
const m = new Map(a)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
Traversal methods
keys()
: returns a traverser for key namesvalues()
: returns a traverser for key valuesentries()
: returns a traverser for key-value pairsforEach()
: Iterates through each member using the callback function
const map = new Map([['a'.1],
['b'.2]])for (let key of map.keys()) {
console.log(key)
}
// "a"
// "b"
for (let value of map.values()) {
console.log(value)
}
/ / 1
/ / 2
for (let item of map.entries()) {
console.log(item)
}
// ["a", 1]
// ["b", 2]
/ / or
for (let [key, value] of map.entries()) {
console.log(key, value)
}
// "a" 1
// "b" 2
// for... of... Traversing a map is equivalent to using map.entries()
for (let [key, value] of map) {
console.log(key, value)
}
// "a" 1
// "b" 2
Copy the code
Data type conversion
Map to array
let map = new Map(a)let arr = [...map]
Copy the code
Array to Map
Map: map = new Map(arr)
Copy the code
Map to object
let obj = {}
for (let [k, v] of map) {
obj[k] = v
}
Copy the code
Object to Map
for( let k of Object.keys(obj)) {map.set(k,obj[k])}Copy the code
The application of the Map
In some Admin projects, we usually display personal information, such as the following information on the page. The traditional approach is as follows.
<div class="info-item">
<span>The name</span>
<span>{{info.name}}</span>
</div>
<div class="info-item">
<span>age</span>
<span>{{info.age}}</span>
</div>
<div class="info-item">
<span>gender</span>
<span>{{info.sex}}</span>
</div>
<div class="info-item">
<span>Mobile phone no.</span>
<span>{{info.phone}}</span>
</div>
<div class="info-item">
<span>Home address</span>
<span>{{info.address}}</span>
</div>
<div class="info-item">
<span>Home address</span>
<span>{{info.duty}}</span>
</div>
Copy the code
Js code
mounted() {
this.info = {
name: 'jack'.sex: 'male'.age: '28'.phone: '13888888888'.address: 'Guangzhou, Guangdong Province'.duty: 'General Manager'}}Copy the code
We use Map to transform, save the label and value we need to display in our Map and render to the page, which reduces a lot of HTML code
<template>
<div id="app">
<div class="info-item" v-for="[label, value] in infoMap" :key="value">
<span>{{label}}</span>
<span>{{value}}</span>
</div>
</div>
</template>
Copy the code
Js code
data: (a)= > ({
info: {},
infoMap: {}
}),
mounted () {
this.info = {
name: 'jack'.sex: 'male'.age: '28'.phone: '13888888888'.address: 'Guangzhou, Guangdong Province'.duty: 'General Manager'
}
const mapKeys = ['name'.'gender'.'age'.'phone'.'Home Address'.'identity']
const result = new Map(a)let i = 0
for (const key in this.info) {
result.set(mapKeys[i], this.info[key])
i++
}
this.infoMap = result
}
Copy the code
WeakMap
WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs.
- Only objects are accepted as key names (
null
Values of other types are not accepted as key names - The key name is a weak reference, the key value can be arbitrary, the object that the key name refers to can be garbage collected, in which case the key name is invalid
- I can’t iterate. I have a method
get
,set
,has
,delete
conclusion
Set
- Is a data structure called collections (new in ES6)
- Members are unique, unordered, and non-repetitive
[value, value]
, the key value is the same as the key name (or only the key value, no key name)- Allows you to store a unique value of any type, either a primitive value or an object reference
- It can be traversed by the following methods:
add
,delete
,has
,clear
WeakSet
- Members are objects
- Members are weak references that can be collected by the garbage collection mechanism and can be used for saving
DOM
Nodes are less likely to cause memory leaks - I can’t iterate. I have a method
add
,delete
,has
Map
- Is a dictionary-like data structure that is essentially a collection of key-value pairs
- You can traverse, you can convert to any data format
- Operation methods are as follows:
set
,get
,has
,delete
,clear
WeakMap
- Only objects are accepted as key names (
null
Values of other types are not accepted as key names - The key name is a weak reference, the key value can be arbitrary, the object that the key name refers to can be garbage collected, in which case the key name is invalid
- I can’t iterate. I have a method
get
,set
,has
,delete
Recommend the article
Concerned about my public number irregularly share front-end knowledge, progress with you!