Home  >  Article  >  Web Front-end  >  Detailed explanation of Set/WeakSet in ECMAScript6_javascript skills

Detailed explanation of Set/WeakSet in ECMAScript6_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:55:281192browse

ES6 adds a new data destructuring Set, which, like Java's Set, does not store duplicate elements. Set is implemented as a class and needs to be new before use.

var s1 = new Set()
s1.add(1)
s1.add(2)
s1.add(3)
s1.add(1)
 
var s2 = new Set()
s2.add('a')
s2.add('a')
 
// 输出1,2, 3
for (var i of s1 ) {
  console.log(i)
}
// 输出a
for (var i of s2 ) {
  console.log(i)
}

Use Set's add method to add elements above. Repeated additions will not be saved.

The Set constructor can also accept arrays as parameters

var s3 = new Set([1,2,3,1])
s3.size // 3

You can see that the repeated number 1 is still not put in. In addition, to get the length of the Set, use size, not length.

It should be noted that for {} or [], they are two same objects

var s4 = new Set()
s4.add({})
s4.add({})
s4.size // 2

1. Traverse Set (for of)

var s1 = new Set()
s1.add(1)
s1.add(2)
s1.add(3)
 
// 输出1,2, 3
for (var i of s1) {
  console.log(i)
}

2. Convert Set into array

var s1 = new Set()
s1.add(1)
s1.add(2)
 
// toArray
var a1 = Array.from(s1)
Array.isArray(a1) // true
 
// or
var a1 = [...new Set(s1)] 

3. Use Set to deduplicate arrays

function distinct(arr) {
  return Array.from(new Set(arr))
// return [...new Set(arr)]
}

as

Attributes of Set

constructor
size
Set method

has(val) determines whether the element exists
add(val) adds element
delete(val) delete element
clear removes all elements
keys
values
entries
forEach traverses elements
map
filter

4. WeakSet

WeakSet and Set do not store duplicate elements, but there are some differences

1. Only store object type elements

ws = new WeakSet()
ws.add(1)

The error reported under FF is as follows

2. There are only three methods add/delete/clear/has, which cannot be traversed, and there is no size attribute, etc.

ws = new WeakSet()
ws.size // undefined
ws.forEach // undefined

MDN’s explanation

The object values ​​stored in the WeakSet object are weakly referenced. If no other variables or attributes refer to the object value, the object value will be garbage collected. Because of this, the WeakSet object cannot be enumerated For example, there is no way to get all the elements it contains

WeakSet is mainly used to store DOM nodes. When these nodes are removed from the document, they will not cause memory leaks.

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn