Loading lesson path
Concept visual
Start at both ends
Set Methods & Properties new Set() add() clear() delete() entries() forEach() has() keys() values() size
constructor:
// Create a new Set const letters = new Set(["a","b","c"]);Example letters.add("d");
letters.add("e");If you add equal elements, only the first will be saved:
Example letters.add("a");
letters.add("b");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");The primary feature of Set objects is that they only store unique values. If an attempt is made to add an element that already exists in the set, the add() method will have no effect, and the set will remain unchanged.
// Create a new Set const mySet = new Set(["a","b","c"]);
// The number of elements are mySet.size;You can list all Set elements (values) with 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;
}method returns true if a specified value exists in a set.
// Create a Set const letters = new Set(["a","b","c"]);
// Does the Set contain "d"?
answer = letters.has("d");method invokes a function for each Set element:
// Create a Set const letters = new Set(["a","b","c"]);
// List all entries let text = "";
letters.forEach (function(value) {
text += value;
})method returns an Iterator object with 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;
}method returns an Iterator object with the values in a Set: A Set has no keys, so keys() returns the same as values(). 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;
}