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) // false
- 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"]
- 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))
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. .
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const b = [1, 2, [1, 2]] new WeakSet(b) // Uncaught TypeError: Invalid value used in weak set</pre><div class="contentsignin">Copy after login</div></div>
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 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
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning
