Home > Web Front-end > JS Tutorial > A brief introduction to WeakSet in ES6

A brief introduction to WeakSet in ES6

不言
Release: 2018-11-14 16:23:26
forward
3030 people have browsed it

This article brings you a brief introduction to WeakSet in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Overview

WeakSet is similar to Set, but there are some differences:

WeakSet can only store objects, not arbitrary values

WeakSet is not iterable

WeakSet is a weak reference, that is, if there is no variable referencing the value in the WeakSet, it can be easily recycled

Initialization

 new WeakSet([iterable]);
Copy after login

Because only objects can be stored, I think this can only Pass in something like an object array

Object array

new WeakSet([{name:1},{name:2}]) //WeakSet(2){{name:1},{name:2}}
Copy after login

Add

let weakset=new WeakSet()
weakset.add({num:1})
weakset.add({num:2})
Copy after login

Determine whether it already exists

let data={num:1}
let weakset=new WeakSet()
weakset.add(data)
weakset.add({num:2})
weakset.has(data) //true
weakset.has({num:2}) //false
Copy after login

Delete

let data={num:1}
let weakset=new WeakSet()
weakset.add(data)
weakset.add({num:2})
weakset.delete(data) //true
weakset.delete({num:2}) //false
Copy after login

Weak reference feature

let weakset=new WeakSet([{num:1}])
setTimeout(()=>console.log(weakset),3000)
// 3s 后输出,可以看到,数据没了
WeakSet {}
Copy after login


The above is the detailed content of A brief introduction to WeakSet in ES6. 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