Provide an array to the new Set() constructor:
// Create a Set const letters = new Set([“a”,“b”,“c”]); |
letters.add(“d”); letters.add(“e”); |
If you add duplicate elements, only the first one will be stored.
letters.add(“a”); letters.add(“b”); letters.add(“c”); letters.add(“c”); letters.add(“c”); letters.add(“c”); letters.add(“c”); letters.add(“c”); |
You can iterate through all Set elements (values) using a for…of loop.
// Create a Set const letters = new Set([“a”,“b”,“c”]); // List all Elements let text = “”; for (const x of letters) { text += x; } |
The has() method returns true if a specified value is present in a Set.
// Create a Set const letters = new Set([“a”,“b”,“c”]); // Does the Set contain “d”? answer = letters.has(“d”); |
The forEach() method calls a function for each element in a Set.
// Create a Set const letters = new Set([“a”,“b”,“c”]); // List all entries let text = “”; letters.forEach (function(value) { text += value; }) |
The values() method returns an Iterator object containing the values in a Set.
// Create a Set const letters = new Set([“a”,“b”,“c”]); // Get all Values const myIterator = letters.values(); // List all Values let text = “”; for (const entry of myIterator) { text += entry; } |
// Create a Set const letters = new Set([“a”,“b”,“c”]); // List all Values let text = “”; for (const entry of letters.values()) { text += entry; } |
The keys() method returns an Iterator object that contains the values in a Set.
NoteA Set has no keys, so the keys() method returns the same as the values() method. This makes Sets compatible with Maps.
|
// Create a Set const letters = new Set([“a”,“b”,“c”]); // Create an Iterator const myIterator = letters.keys(); // List all Elements let text = “”; for (const x of myIterator) { text += x; } |
// Create a Set const letters = new Set([“a”,“b”,“c”]); // List all Elements let text = “”; for (const x of letters.keys()) { text += x; } |
The entries() method returns an Iterator with [value, value] pairs from a Set.
NoteThe entries() method is intended to return a [key, value] pair from an object. However, since a Set has no keys, the entries() method returns [value, value]. This similarity makes Sets compatible with Maps. |
// Create a Set const letters = new Set([“a”,“b”,“c”]); // Get all Entries const myIterator = letters.entries(); // List all Entries let text = “”; for (const entry of myIterator) { text += entry; } |
// Create a Set const letters = new Set([“a”,“b”,“c”]); // List all Entries let text = “”; for (const entry of letters.entries()) { text += entry; } |