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
-
undefinedIt is identical toundefined, so it is not repeated. -
NaNis not identical toNaN, but it is not repeated inSetconsidersNaNto 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 theSetstructure itself (can be called in a chain). - delete(value)
: Delete a certain value. If the deletion is successful, it will returntrue, otherwise it will returnfalse. - has(value)
: Returns a Boolean value indicating whether the value is a member ofSet. - 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
'sindexOfmethod is better thanSet'shasThe method is inefficient - Set
does not contain duplicate values (you can use this feature to achieve deduplication of an array) - Set
Pass# The ##deletemethod deletes a value, whileArraycan 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,everyetc. 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!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.







