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

A brief introduction to WeakSet in ES6

不言
不言forward
2018-11-14 16:23:063012browse

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]);

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

Add

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

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

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

Weak reference feature

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


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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete