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
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
Special values in Set
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:
- 0 and -0 are identical when storing and judging uniqueness, so they are not repeated
-
undefined
It is identical toundefined
, so it is not repeated. -
NaN
is not identical toNaN
, but it is not repeated inSet
considersNaN
to be equal toNaN
, and only one of them can exist without duplication.
Attributes of Set:
-
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
Set instance object The method
- ##add(value)
: adds a certain value and returns the
Setstructure itself (can be called in a chain).
- delete(value)
: Delete a certain value. If the deletion is successful, it will return
true, otherwise it will return
false.
- has(value)
: Returns a Boolean value indicating whether the value is a member of
Set.
- clear()
: 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
- keys()
: Returns the traverser of key names.
- values()
: Returns the traverser of key values.
- entries()
: Returns a traverser of key-value pairs.
- forEach()
: 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
- Array
's
indexOfmethod is better than
Set's
hasThe method is inefficient
- Set
does not contain duplicate values (you can use this feature to achieve deduplication of an array)
- Set
Pass# The ##delete
method deletes a value, whileArray
can only be passed throughsplice
. The former is better in terms of ease of use of the two. Array - has many new methods
map
,filter
,some
,every
etc. are not available inSet
(but they can be used by converting each other) Application of Set
1,# The ##Array.from
method can convert theSet 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
WeakSet
has a structure similar toSet, and is also a collection of unique values.
The members are all arrays and array-like objects. If the
- method is called with parameters that are not arrays and array-like objects, an error will be thrown. .
<pre class="brush:php;toolbar:false">const b = [1, 2, [1, 2]] new WeakSet(b) // Uncaught TypeError: Invalid value used in weak set</pre>
Members are weak references and can be recycled by the garbage collection mechanism. They can be used to save DOM nodes and are not prone to memory leaks.
- WeakSet is not iterable, so it cannot be used in loops such as
- for-of
.
WeakSet
has no - size
property.
Map
Map
stores key-value pairs in the form ofkey-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.
Map 和 Object 的区别
-
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
的长度, 你只能手动计算
Map 的属性
- size: 返回集合所包含元素的数量
const map = new Map() map.set('foo', ture) map.set('bar', false) map.size // 2
Map 对象的方法
-
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]) }
Map的应用
在一些 Admin 项目中我们通常都对个人信息进行展示,比如将如下信息展示到页面上。传统方法如下。
<p> <span>姓名</span> <span>{{info.name}}</span> </p> <p> <span>年龄</span> <span>{{info.age}}</span> </p> <p> <span>性别</span> <span>{{info.sex}}</span> </p> <p> <span>手机号</span> <span>{{info.phone}}</span> </p> <p> <span>家庭住址</span> <span>{{info.address}}</span> </p> <p> <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> </p> <p> <span>{{label}}</span> <span>{{value}}</span> </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
WeakMap
结构与 Map
结构类似,也是用于生成键值对的集合。
- 只接受对象作为键名(
null
除外),不接受其他类型的值作为键名 - 键名是弱引用,键值可以是任意的,键名所指向的对象可以被垃圾回收,此时键名是无效的
- 不能遍历,方法有
get
、set
、has
、delete
总结
Set
- 是一种叫做集合的数据结构(ES6新增的)
- 成员唯一、无序且不重复
-
[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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)
