Home > Web Front-end > JS Tutorial > Take you to understand ES6 Set, WeakSet, Map and WeakMap

Take you to understand ES6 Set, WeakSet, Map and WeakMap

hzc
Release: 2020-06-20 09:43:34
forward
2482 people have browsed it

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
Copy after login

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 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.

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
Copy after login

Set instance object The method

  • ##add(value): adds a certain value and returns the Set structure 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
Copy after login
Traversal 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.
Since the

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"]
Copy after login
Comparison between Array and Set

  • Array's indexOf method is better than Set's has The 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, while Array can only be passed through splice. 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 in Set (but they can be used by converting each other)
  • Application of Set

1,# The ##Array.from

method can convert the

Set structure into an array.

const items = new Set([1, 2, 3, 4, 5])
const array = Array.from(items)
Copy after login
2. Array deduplication
// 去除数组的重复成员
;[...new Set(array)]

Array.from(new Set(array))
Copy after login
3. The

map

and

filter 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}
Copy after login
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}
Copy after login
weakSet

WeakSet

has a structure similar to

Set, and is also a collection of unique values. The members are all arrays and array-like objects. If the

add()
    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 of

key-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 的区别

  1. Object 对象有原型, 也就是说他有默认的 key 值在对象上面, 除非我们使用 Object.create(null)创建一个没有原型的对象;
  2. Object 对象中, 只能把 StringSymbol 作为 key 值, 但是在 Map 中,key 值可以是任何基本类型(String, Number, Boolean, undefined, NaN….),或者对象(Map, Set, Object, Function , Symbol , null….);
  3. 通过 Map 中的 size 属性, 可以很方便地获取到 Map 长度, 要获取 Object 的长度, 你只能手动计算

Map 的属性

  • size: 返回集合所包含元素的数量
const map = new Map()
map.set('foo', ture)
map.set('bar', false)
map.size // 2
Copy after login

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
Copy after login

遍历方法

  • 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
Copy after login

数据类型转化

Map 转为数组

let map = new Map()
let arr = [...map]
Copy after login

数组转为 Map

Map: map = new Map(arr)
Copy after login

Map 转为对象

let obj = {}
for (let [k, v] of map) {
  obj[k] = v
}
Copy after login

对象转为 Map

for( let k of Object.keys(obj)){
  map.set(k,obj[k])
}
Copy after login

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>
Copy after login

js 代码

mounted() {
  this.info = {
    name: 'jack',
    sex: '男',
    age: '28',
    phone: '13888888888',
    address: '广东省广州市',
    duty: '总经理'
  }
}
Copy after login

我们通过 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>
Copy after login

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
}
Copy after login

WeakMap

WeakMap 结构与 Map 结构类似,也是用于生成键值对的集合。

  • 只接受对象作为键名(null 除外),不接受其他类型的值作为键名
  • 键名是弱引用,键值可以是任意的,键名所指向的对象可以被垃圾回收,此时键名是无效的
  • 不能遍历,方法有 getsethasdelete

总结

Set

  • 是一种叫做集合的数据结构(ES6新增的)
  • 成员唯一、无序且不重复
  • [value, value],键值与键名是一致的(或者说只有键值,没有键名)
  • 允许储存任何类型的唯一值,无论是原始值或者是对象引用
  • 可以遍历,方法有:adddeletehasclear

WeakSet

  • 成员都是对象
  • 成员都是弱引用,可以被垃圾回收机制回收,可以用来保存 DOM 节点,不容易造成内存泄漏
  • 不能遍历,方法有 adddeletehas

Map

  • 是一种类似于字典的数据结构,本质上是键值对的集合
  • 可以遍历,可以跟各种数据格式转换
  • 操作方法有:setgethasdeleteclear

WeakMap

  • 只接受对象作为键名(null 除外),不接受其他类型的值作为键名
  • 键名是弱引用,键值可以是任意的,键名所指向的对象可以被垃圾回收,此时键名是无效的
  • 不能遍历,方法有 getsethasdelete

推荐教程:《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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template