Set up JavaScript data structure

The Set data structure allows data to be added to a collection of containers, objects, or primitive types (strings, numbers, or booleans), and you can think of it as a Map using values as map keys, where the map value is always a boolean true.

What is a suit

The Set data structure allows data to be added to the container.

ECMAScript6 (also known as ES2015) introduced the Set data structureJavaScriptThe world, andmap

Set is a collection of objects or primitive types (string, number, or boolean), you can think of it as a Map, where the value is used as the map key, and the map value is always the boolean true.

Initialize the collection

Initialize Set in the following way:

const s = new Set()

Add items to the collection

you can use itaddmethod:

s.add('one')
s.add('two')

The collection only stores unique elements, so calls.add('one')No new items will be added multiple times.

You cannot add multiple elements to the collection at the same time. You need to calladd()repeatedly.

Check if the item is in the collection

Once the element enters the collection, we can check whether the collection contains it:

s.has('one') //true
s.has('three') //false

Delete items from "Key Settings"

usedelete()method:

s.delete('one')

Determine the number of items in the collection

usesizeproperty:

s.size

Delete all items in the collection

useclear()method:

s.clear()

Projects in the iterative focus

usekeys()orvalues()Methods-they are equivalent:

for (const k of s.keys()) {
  console.log(k)
}

for (const k of s.values()) { console.log(k) }

Thisentries()The method returns an iterator, and you can use it like this:

const i = s.entries()
console.log(i.next())

calli.next()Returns each element as{ value, done = false }Object until the end of the iteratordoneYestrue.

You can also use the forEach() method on the collection:

s.forEach(v => console.log(v))

Or you can use the collection in a for..of loop:

for (const k of s) {
  console.log(k)
}

Initialize the collection with a value

You can initialize the Set with a set of values:

const s = new Set([1, 2, 3, 4])

Convert to array

Convert the Set key to an array

const a = [...s.keys()]

// or const a = […s.values()]

Weak set

WeakSet is a special set.

In Set, items are never garbage collected. On the contrary, WeakSet allows free garbage collection of all its items. Each key of the WeakSet is an object. When the reference to the object is lost, the value can be garbage collected.

The main differences are as follows:

  1. You cannot traverse the WeakSet
  2. You cannot clear all items from WeakSet
  3. You can't check its size

WeakSet is usually used by framework-level code and only exposes the following methods:

  • Add to()
  • Already ()
  • delete()

Download mine for freeJavaScript beginner's manual


More js tutorials: