How to use Set and WeakSet_javascript in ES6

Source: Internet
Author: User
This article describes in detail how to use Set and WeakSet in ES6. If you are interested, refer to the two new data structures-Set and WeakSet in ES6. Set is similar to an array, but the values of member variables are unique and there are no repeated values. WeakSet is also a set of non-repeated values, but can only be used to store objects.

1. Set usage

(1) Set itself provides a constructor to generate a 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 construction parameter for initialization.

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

Note:No type conversion will occur when values are added to the Set. Therefore, "5" and "5" are two different values. In the Set, determine whether the two values are equal and use =, this means that these two objects are always not equal. The unique column is NaN itself (exact equality operator considers NaN not equal to itself)

let set = new Set();set.add({})set.size//1set.add({})set.size//2

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

(3) Set methods and attributes

(3.1) Set attributes

Set. prototype. size: returns the number of members of the Set instance.
Set. prototype. constructor: default constructor.

(3.2) Set operation Ah Function

Add (value): add a value and return the Set structure itself.
Delete (value): delete a value. A boolean value is returned, indicating that the deletion is successful.
Has (value): returns a Boolean value indicating whether the parameter is a member of the Set.
Clear (): clear all members without returning values.

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

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

(3.3) Set traversal operation

Set has four traversal methods. It can be used to traverse members.
Keys (): returns a traversal tool with a key name.
Values (): returns the traversal of a value.
Entries (): returns the traversal of a key-value pair.
ForEach (): Use the callback function to traverse each member.

Note: Because Set does not have a key name and only has a value name, The results returned by keys () and values () are the same,

Let set = new Set (['red', 'green', 'blue']); for (let item of set. keys () {console. log (item);} // red, green, bluefor (let item of set. values () {console. log (item);} // red, green, bluefor (let item of set. entries () {console. log (item);} // ["red", "red"] // ["green", "green"] // ["blue ", "blue"] // Therefore, the traversal Tool returned by the entries method includes both the key name and value, so each time an array is output. In fact, the members are all the same.

Note: The default traversal function of Set is its values method.
This means that the values method can be omitted and the... Of traversal.

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 (...) Internal use of... Of loop, so it can also be used in the Set structure.

let set = new Set(['red','green','blue']);let arr = [...set];//['red','green','blue'];

(3.4) Set implements union, intersection, and difference

Let set1 = new Set ([,]); let set2 = new Set ([,]); // union 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) use Set to implement 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 parameter of the forEach method is a processing function, which is the Set (key value, key name) in turn. In addition, the forEach method has a second parameter, indicating the object bound with this.

Ii. Use WeakSet

WeakSet is similar to Set and is also a Set of non-repeated values. However, it can only be used to store objects. It cannot be a value of another type.
WeakSet is a constructor. Objects of arrays and similar Arrays can be used as parameters. (In fact, any object used as the iterable interface can be used as a WeakSet parameter ). All members of the array will automatically become members of the WeakSet instance object.
Var a = new [[1, 2], [3, 4];
Var ws = new WeakSet ();

var ws = new WeakSet();ws.add(1);//TypeError:Invalid value used in weak set ws.add(Symbol);//TypeError:Invalid value used in weak set 

If a value and a Symbol are added, an error is returned at the same time.

The WeakSet structure has the following methods:
WeakSet. protoptype. add (value): add a new member to the WeakSet instance.
WeakSet. protoptype. delete (value): deletes a specified member of a WeakSet instance.
WeakSet. protoptype. has (value): returns a Boolean value indicating 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);//truews.has(foo);falsews.delete(window);//truews.has(window);//false

WeakSet cannot be traversed because the Members are weak references and may disappear at any time. traversal cannot ensure the existence of members. The traversal may have just ended and the Members cannot be retrieved. One use of WeakSet is to store DOM nodes without worrying about memory leakage when these nodes are removed from the document.

Related Article

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.