How to use Set and weakset_javascript techniques in ES6

Source: Internet
Author: User
Tags data structures new set

The ES6 provides two new data structures-set and Weakset. The set is similar to an array, but the value of the member variable is unique and there is no duplicate value. Weakset is also a collection of values that are not duplicates, but can only be used to store objects.

One, set use

(1) The set itself provides a constructor that is used to generate the set data structure.

var s = new Set ();
[2,2,2,5,8,16,2,1].map (x => s.add (x)) for

(I of S) {Console.log (i)}
//2,5,8,16,1

(2) The Set () function can accept an array as a constructor parameter for initialization.

var s = new Set ([1,2,3,4,2,4,3]);
[... s]
[1,2,3,4]

Note: When you add a value to a set, no type conversions occur, so 5 and "5" are two different values, and the set inside determines whether two values are equal and uses = =, which means that the two objects are always unequal. The only column is the Nan itself (the exact equality operator thinks Nan is not equal to itself)

Let set = new set ();
Set.add ({})
set.size//1
set.add ({})
SET.SIZE//2

, the code above indicates that because these two empty objects are not exactly equal, they are two different values.

(3) Set's methods and properties

(3.1) Set's properties

Set.prototype.size: Returns the number of members of the set instance.
Set.prototype.constructor: The default constructor set function.

(3.2) Set's Operation Ah function

Add: Adds a value that returns the set structure itself.
Delete (value): Deletes a value, returns a Boolean value, indicating that the deletion was successful.
Has (value): Returns a Boolean value that indicates whether the parameter is a member of set.
Clear (): Clears all Members, no return value.

var set = new set ();
Set.add (1). Add (2). Add (22);
Set.size//3

Set.hae (//true)
Set.has (4)//false
Set.delete (2)//true

(3.3) Set traversal operation

Set has four traversal methods. Can be used to traverse members.
Keys (): Returns an iterator for a key name
VALUES (): a loop that returns a value
Entries (): Returns an iterator for a key-value pair
ForEach (): Use callback function to traverse each member

Note: Since set does not have a key name, only the value name, the keys () and values () return the same result.

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"]

//So the loop returned by the entries method includes both the key name and the value, so each output is an array. In fact, the members are all exactly the same.

Note: Set default traversal, its default iterator generation function is its values method.
This means that the values method can be omitted and traversed directly with For...of.

var set = new set ([1,2,3,4]);
for (Let X of Set) {
console.log (x);
}
1
//2
//3
//4

If you use the extension operator (...). The For...of loop is used internally, so it can also be used for the set structure.

Let set = new set ([' Red ', ' green ', ' blue ']);
Let arr = [... set];
[' Red ', ' green ', ' Blue '];

(3.4) Set implementation and set, intersection, difference set

Let Set1 = new Set ([1,2,3,4,5,6]);
Let Set2 = new Set ([4,5,6,7,8,9]);

and set let
union = new Set ([... Set1,... Set2]);
[1,2,3,4,5,6,7,8,9]
//intersection let
intersect = new Set ([... set1].filter (x => b.has (s)));
[4,5,6]
//difference set let
intersect = new set ([... set1].filter (x =>!b.has (s)));
[1,2,3,4]

(3.5) Set implements the use of foreach

Let set = New set ([1,2,3,4,5,6]);
Set.foreach (Value,key) =>consloe.log (vlaue+1);
2
//3
//4
//5
//6
//7

Note:The parameters of the Foreach method are a handler function, which in turn is (the key value, the key name) the collection itself. In addition, the Foreach method has a second parameter that represents the object that binds this.

Second, the use of Weakset

Weakset is similar to set and is a collection of values that are not duplicates. But it can only be used to store objects. It cannot be a value of another type.
Weakset is a constructor. You can accept arrays and similar arrays of objects as parameters. (In fact, any object with a iterable interface can be used as a weakset parameter). All members of the array automatically become members of the instance object of the Weakset.
var a = new [[1,2],[3,4]];
var ws = new Weakset (a);

var ws = new Weakset ();
Ws.add (1);//typeerror:invalid value used in weak set 

Add as a number and a symbol, and the result is an error.

The WEAKSET structure has the following upper method
WeakSet.protoptype.add (value): Adds a new member to the Weakset instance.
WeakSet.protoptype.delete (value): Deletes a Weakset instance to specify a member.
WeakSet.protoptype.has (value): Returns a Boolean value that indicates whether a value is in the Weakset instance.

var ws = new Weakset ();
var obj = {};
var foo = {};
Ws.add (window);
Ws.add (obj);
Ws.has (window);//true
Ws.has (foo); false
ws.delete (window);//true
Ws.has (window);//false

Weakset cannot traverse because members are weak references and may disappear at any time, and traversal does not guarantee the presence of members. It may be just the end of the traversal, members will not be taken. One use of Weakset is to store DOM nodes without worrying that the nodes will cause memory leaks when they are removed from the document.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.