WeakSet is similar to Set. It is also a collection with non-repeating elements. The difference between them is that the elements in WeakSet must be objects and cannot be other types. Next, this article will give you a detailed introduction to the usage of ES6's new data structure WeakSet. Friends who are interested should take a look.
WeakSet is similar to Set. They are also collections with non-repeating elements. The difference between them is that the contents of WeakSet The elements must be objects and cannot be of other types.
Characteristics:
1. The element must be an object.
Add an element of type number.
const ws = new WeakSet() ws.add(1)
The result is a type error.
TypeError: Invalid value used in weak set
Add an object.
const ws = new WeakSet() var a = {p1:'1', p2:'2'} ws.add(a) console.log(ws.has(a));
Add OK, the result shows:
true
You can use the has method of WeakSet to determine whether an element is already in the set.
If you do not need to store elements, you can use the delete method to delete elements.
2. Weak references are not included in garbage collection
For element objects added to WeakSet, WeakSet will not increase the reference count of the element object by 1. For The element object added to the WeakSet will be released by garbage collection as long as the element object is not referenced by other objects other than the WeakSet. The element object in the WeakSet will be automatically released without memory leaks.
Because of this feature, its performance is higher than map. It can be used for scenarios that require non-sequential storage, non-repetition, and temporary storage.
const ws = new WeakSet() var a = {p1:'1', p2:'2'} ws.add(a) a = null console.log(ws.has(a));
First add the object to the WeakSet, then set the object to null, and then when the has method is judged below, the result is displayed, indicating that the object no longer exists in the WeakSet object.
false
3. Cannot traverse
Because it has a weak reference to the internal element object and will be released by garbage collection at any time, so it Traversal methods such as size and forEach are not supported.
The above is the detailed content of Detailed introduction to the new WeakSet data structure in ES6. For more information, please follow other related articles on the PHP Chinese website!