Home >Web Front-end >JS Tutorial >Take you to understand ES6 Set, WeakSet, Map and WeakMap
When I was learning ES6 before, I saw Set
and Map
. I didn’t know what their application scenarios were. I just thought they were often used in array deduplication and data storage. Later, I slowly realized that Set
is a data structure called a set, and Map
is a data structure called a dictionary.
This article is included in gitthub: github.com/Michael-lzg…
Set
itself is a constructor used to generate Set
Data structure. Set
The function can accept an array (or other data structure with iterable interface) as a parameter for initialization. Set
Objects allow you to store any type of value, whether it is a primitive value or an 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() [2, 3, 5, 4, 5, 2, 2].forEach((x) => s.add(x)) for (let i of s) { console.log(i) } // 2 3 5 4
Set
The value stored in the object is always unique, so it is necessary to determine whether the two values are equal. There are several special values that require special treatment:
undefined
It is identical to undefined
, so it is not repeated. NaN
is not identical to NaN
, but it is not repeated in Set
considers NaN
to be equal to NaN
, and only one of them can exist without duplication. size
: Returns the number of elements contained in the set const items = new Set([1, 2, 3, 4, 5, 5, 5, 5]) items.size // 5
: adds a certain value and returns the
Set structure itself (can be called in a chain).
: Delete a certain value. If the deletion is successful, it will return
true, otherwise it will return
false.
: Returns a Boolean value indicating whether the value is a member of
Set.
: Clear all members, no return value.
s.add(1).add(2).add(2) // 注意2被加入了两次 s.size // 2 s.has(1) // true s.has(2) // true s.has(3) // false s.delete(2) s.has(2) // falseTraversal method
: Returns the traverser of key names.
: Returns the traverser of key values.
: Returns a traverser of key-value pairs.
: Use the callback function to traverse each member.
Set structure has no key name, only key value (or key name and key value are the same value), so the
keys method is the same as
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"]Comparison between Array and Set
's
indexOf method is better than
Set's
has The method is inefficient
does not contain duplicate values (you can use this feature to achieve deduplication of an array)
Pass# The ##delete
method deletes a value, while Array
can only be passed through splice
. The former is better in terms of ease of use of the two.
map
, filter
, some
, every
etc. are not available in Set
(but they can be used by converting each other)
Set structure into an array.
const items = new Set([1, 2, 3, 4, 5]) const array = Array.from(items)
2. Array deduplication
// 去除数组的重复成员 ;[...new Set(array)] Array.from(new Set(array))3. The
map
andfilter methods of the array can also be used indirectly for
Set
let set = new Set([1, 2, 3]) set = new Set([...set].map((x) => x * 2)) // 返回Set结构:{2, 4, 6} let set = new Set([1, 2, 3, 4, 5]) set = new Set([...set].filter((x) => x % 2 == 0)) // 返回Set结构:{2, 4}
4. Implement union
(Union), intersection(Intersect) and difference set
let a = new Set([1, 2, 3]) let b = new Set([4, 3, 2]) // 并集 let union = new Set([...a, ...b]) // Set {1, 2, 3, 4} // 交集 let intersect = new Set([...a].filter((x) => b.has(x))) // set {2, 3} // 差集 let difference = new Set([...a].filter((x) => !b.has(x))) // Set {1}
weakSet
Set, and is also a collection of unique values.
The members are all arrays and array-like objects. If the
<pre class="brush:php;toolbar:false">const b = [1, 2, [1, 2]]
new WeakSet(b) // Uncaught TypeError: Invalid value used in weak set</pre>
.
WeakSet property.
Mapkey-value, where
key and
value can be of any type, that is, objects can also be used as
key. The emergence of
Map allows various types of values to be used as keys.
Map provides "value-value" correspondence.
Object
对象有原型, 也就是说他有默认的 key
值在对象上面, 除非我们使用 Object.create(null)
创建一个没有原型的对象;Object
对象中, 只能把 String
和 Symbol
作为 key
值, 但是在 Map
中,key
值可以是任何基本类型(String
, Number
, Boolean
, undefined
, NaN
….),或者对象(Map
, Set
, Object
, Function
, Symbol
, null
….);Map
中的 size
属性, 可以很方便地获取到 Map
长度, 要获取 Object
的长度, 你只能手动计算const map = new Map() map.set('foo', ture) map.set('bar', false) map.size // 2
set(key, val)
: 向 Map
中添加新元素get(key)
: 通过键值查找特定的数值并返回has(key)
: 判断 Map
对象中是否有 Key
所对应的值,有返回 true
,否则返回 false
delete(key)
: 通过键值从 Map
中移除对应的数据clear()
: 将这个 Map
中的所有元素删除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
keys()
:返回键名的遍历器values()
:返回键值的遍历器entries()
:返回键值对的遍历器forEach()
:使用回调函数遍历每个成员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] // 或者 for (let [key, value] of map.entries()) { console.log(key, value) } // "a" 1 // "b" 2 // for...of...遍历map等同于使用map.entries() for (let [key, value] of map) { console.log(key, value) } // "a" 1 // "b" 2
Map 转为数组
let map = new Map() let arr = [...map]
数组转为 Map
Map: map = new Map(arr)
Map 转为对象
let obj = {} for (let [k, v] of map) { obj[k] = v }
对象转为 Map
for( let k of Object.keys(obj)){ map.set(k,obj[k]) }
在一些 Admin 项目中我们通常都对个人信息进行展示,比如将如下信息展示到页面上。传统方法如下。
<p class="info-item"> <span>姓名</span> <span>{{info.name}}</span> </p> <p class="info-item"> <span>年龄</span> <span>{{info.age}}</span> </p> <p class="info-item"> <span>性别</span> <span>{{info.sex}}</span> </p> <p class="info-item"> <span>手机号</span> <span>{{info.phone}}</span> </p> <p class="info-item"> <span>家庭住址</span> <span>{{info.address}}</span> </p> <p class="info-item"> <span>家庭住址</span> <span>{{info.duty}}</span> </p>
js 代码
mounted() { this.info = { name: 'jack', sex: '男', age: '28', phone: '13888888888', address: '广东省广州市', duty: '总经理' } }
我们通过 Map 来改造,将我们需要显示的 label 和 value 存到我们的 Map 后渲染到页面,这样减少了大量的html代码
<template> <p id="app"> <p class="info-item" v-for="[label, value] in infoMap" :key="value"> <span>{{label}}</span> <span>{{value}}</span> </p> </p> </template>
js 代码
data: () => ({ info: {}, infoMap: {} }), mounted () { this.info = { name: 'jack', sex: '男', age: '28', phone: '13888888888', address: '广东省广州市', duty: '总经理' } const mapKeys = ['姓名', '性别', '年龄', '电话', '家庭地址', '身份'] const result = new Map() let i = 0 for (const key in this.info) { result.set(mapKeys[i], this.info[key]) i++ } this.infoMap = result }
WeakMap
结构与 Map
结构类似,也是用于生成键值对的集合。
null
除外),不接受其他类型的值作为键名get
、set
、has
、delete
Set
[value, value]
,键值与键名是一致的(或者说只有键值,没有键名)add
、delete
、has
、clear
WeakSet
DOM
节点,不容易造成内存泄漏add
、delete
、has
Map
set
、get
、has
、delete
、clear
WeakMap
null
除外),不接受其他类型的值作为键名不能遍历,方法有 get
、set
、has
、delete
推荐教程:《JS教程》
The above is the detailed content of Take you to understand ES6 Set, WeakSet, Map and WeakMap. For more information, please follow other related articles on the PHP Chinese website!