In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian introduces in detail "how to use the collection of Set and WeakSet in ES6", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to use the collection of Set and WeakSet in ES6" can help you solve your doubts.
Set is a special set of values that never repeat.
Use arrays every day. Have you ever had a Moment worried about inserting duplicate values? Use Set collections! Set has a special data structure that ensures that inserted values are never duplicated.
Set Collection Base API
Create a Set instance through the Set.prototype.constructor constructor
/ * * instantiation only: call the constructor without passing the parameter * / let empty_set = new Set () / * * instantiate and initialize: pass in any iterate object Convert it to Set set * / let transfer_set4arr = new Set ([1,2,3]) / return Set (3) {1,2,3} let transfer_set4string = new Set ("huilin") / / return Set (5) {"h", "u", "I", "l", "n"} let transfer_set4set = new Set (new Set ([5,6])) / / return Set (2) {5,6}
Access the Set.prototype.size property to return the number of elements in the collection
Console.log (empty_set.size) / / 0console.log (transfer_set4arr.size) / / 3
Call the Set.prototype.has (value) method to determine whether the element exists
/ / Set.has () performs better than Array.includes () because it optimizes the member test console.log (empty_set.has (1)) / / falseconsole.log (transfer_set4arr.has ("h")) / / true's judgment on unique values
In order to ensure the uniqueness of the value, the Set set uses Object.is (value1,value2) to judge, rather than by the = = (identity symbol) symbol, because identity judgment will cast the variables on both sides.
For example, the values of both variables are NaN, or 0 and-0, which is not equal by JS, but Object.is () thinks it is the same only, so it cannot be stored in the Set set.
To learn more about Object.is (), please jump to see: developer.mozilla.org/zh-CN/docs/...
Let N1 = NaNlet N2 = NaNconsole.log (N1 = = N2) / / identity symbol judgment is inconsistent, output falseconsole.log (Object.is (N1) N2) / / but Object.is () determines that the two are the same, and the output false// Set set does not allow two NaN to be put into the set let set = new Set () set.add (N1) .add (N2) console.log (set.size) / / size: 1
In the face of complex data types, it is mainly judged by the reference of the object. References are inconsistent, and even if the data structure is consistent, they are considered to be only different, so they can be stored in the Set collection.
Let same_value_set = new Set (); / / save an object same_value_set.add ({num: 0}) first; / / save a new object with consistent structure let obj = {num: 0}; same_value_set.add (obj); / / all can be saved into successful console.log (same_value_set.size); / / 2
Call the Set.prototype.add (value) method to append data to the collection
The / / add () method can append any type of data, either the original value or the object reference let set1 = new Set () / / since the add () method always returns a reference to the current instance, make a chained call to set1.add (1) .add (2) .add (3) console.log (set1) / / Set (3) {1,2,3} / / Note: when add () is passed into the array Set inserts the array instance into the collection instead of the element set1.add ([4,5]) console.log (set1) / / Set (4) {1,2,3, [4,5]} in the array
Call the Set.prototype.delete (value) method to remove elements from the collection
The / / delete () method returns whether the removal operation was successful, just like the .has () method let success = set1.delete (1) console.log (success) / / true
Call the Set.prototype.clear () method to empty the collection
Let num_set = new Set ([1,6,3]) console.log (num_set) / / Set (3) {1,6,3} set1.clear () console.log (num_set) / / Set (0) {} Set set traversal
Because the collection does not have a subscript / index, it is generally considered an "unordered collection". But JavaScript remembers the order in which elements are inserted, so the elements are iterated sequentially as they are traversed.
Traverse the Set collection directly
Let set = new Set ([1,2,3,4,5]) for (let item of set) {console.log (item)} / / output: 1 2 3 4 5
Create an iterator to traverse
/ * * there are three ways to create an iterator * Set.prototype.entries () * Set.prototype.keys () * Set.prototype.values () * / / Set collection has only value but no key, but to make it similar to traversing the Map object, Set.entries () creates a new Iterator object with equal keys and values for each item That is, [value,value] for (let [key,value] of set.entries ()) {console.log (value)} / / output in turn: 1 2 3 45 for / Set.keys () create a new Iterator object, return each value for (let key of set.keys ()) {console.log (key)} / / output in turn: 1 2 3 4 5 shock / Set.values () is consistent with Set.keys () Return the value of each item for (let value of set.values ()) {console.log (value)} / / output in turn: 1 2 3 4 5
Call the Set.prototype.forEach (callbackFn) method to traverse
/ / forEach (callbackFn) calls callbackFn in insertion order, and takes out each item value set.forEach (item = > {console.log (item)}) / / outputs: 1 2 3 4 5Set collection case practice
Conversion between Set set and Array array
/ * * Set to Array * / let set1 = new Set ([1,2,3]) / / Array.from () method let arr1 = Array.from (set1) / / extension operator let arr2 = [... set1] / * * Array to Set * / / use the Set constructor let set = new Set (array) single array to demultiply let set = new Set ([1,2,4,4,2,5]) console.log (set) / / Set (4) {1,2) 4, 5} multiple arrays merge and deduplicate let arr1 = [1,2,4] let arr2 = [1,5,6] / / make use of the characteristics of Set sets The elements in the collection are unique let result = new Set ([... set1,... set2]) console.log (result) / / Set (5) {1,2,4,5,6} get intersection (duplicate elements) let set1 = new Set ([1,2,4]) let set2 = new Set ([1,5]) 6]) / / returns the element let result = new Set ([... set1] .filter (x = > set2.has (x) console.log (result) / / Set (1) {1} where both set1 and set2 exist. Determine whether there is an intersection (duplicate elements) let set1 = new Set ([1,2,4]) let set2 = new Set ([1,5,6]) function isMixed (set) Subset) {for (let elem of subset) {if (set.has (elem)) {return true }} return false } console.log (isMixed (set1, set2)) / / true get difference: only repeat let set1 = new Set ([1,2,4]) let set2 = new Set ([1,5,6]) function difference (setA, setB) {let result = new Set () for (let elem of setB) {if (setA.has (elem)) {result.add (elem)} return result } where is the "weak" of console.log (difference (set1, set2)) WeakSet?
In addition to the Set collection, ES6 also provides WeakSet and WeakMap. Since the name of the set is "Weak", where on earth is it "weak"?
Weak function
WeakSet does not allow the insertion of original values and only supports references to objects.
Let val1 = {id: 1}, val2 = {id: 2} let ws = new WeakSet () / / like the Set collection, the value of WeakSet is not duplicated, and add () also returns the collection instance. So you can chain operation ws.add (val1) .add (val1) .add (val2) / / do not allow the insertion of the underlying data type ws.add (3) / / error: TypeError:Invalid value used in WeakSet// but can be wrapped into an object before inserting let val3 = new Number (3) ws.add (val3) console.log (ws.has (val3)) / / output: true
WeakSet only implements three operation methods: add (), has () and delete ().
WeakSet does not allow traversal, and there are no size or length properties
Weak reference
To talk about weak references, first look at what strong references are:
/ / declare an object let handsome = {name: "huilin", age: 30} / / put in the array let arr = [1, handsome, 2] console.log ("release before arr length", arr.length) / / 3Maplet user / put in Maplet user = {oid: 10001, classify: "Chinese", staffReference: handsome} console.log ("release before map length") Object.keys (user) .length) / / 3console.log ("-") / / suddenly places the object in a container with nullhandsome = null// strong reference The object still exists unrecycled console.log ("release after arr length", arr.length) / / 3console.log (arr [1]) / / {name: "huilin", age: 30} console.log ("release after map length", Object.keys (user) .length) / / 3console.log (user.staffReference) / / {name: "huilin", age: 30}
From the test code, the referenced object has not been recycled unless the container is destroyed. The so-called weak reference means that the container is expected to scale automatically according to the element, and once the object is null, the references in the container are also recycled.
Let obj1 = {name: "huilin", age: 30} let obj2 = {name: "cc", age: 29} let ws1 = new WeakSet () ws1.add (obj1) .add (obj2) console.log (ws1.has (obj1)) / / true// either from the container operation element ws1.delete (obj1) console.log (ws1.has (obj1) / / false// or from the object itself to null Will automatically recycle obj2 = nullconsole.log (ws1.has (obj2)) / / false read here, this article "how to use the collection of Set and WeakSet in ES6" has been introduced, to master the knowledge of this article, you still need to do your own practice in order to understand, if you want to know more related articles, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.