JS set: основные принципы и применение
JS Set
JS Set is a data structure in JavaScript that represents a collection of unique values. This means that each value in a Set can only be represented once, and duplicates are automatically ignored. Set in JavaScript is similar to an array, but it has several features that make it convenient for working with sets of data.
To create a Set in JavaScript, we can use the new Set() operator, or pass an iterable object to the Set constructor, which allows us to add initial values directly during creation. For example:
let mySet = new Set(); // creating an empty Set
let mySet2 = new Set([1, 2, 3, 4, 5]); // creating a Set with initial values
The Set methods allow us to add, delete, and check for the presence of elements. Here are some examples of Set methods.
The add(value) method: adds elements to the Set:
mySet.add(6); mySet.add("Hello");The delete(value) method: deletes elements from the Set:
mySet.delete(6);The has(value) method: checks if the Set contains the specified value:
mySet.has("Hello"); // trueThe size method: returns the number of elements in the Set:
mySet.size; // 1The clear method: removes all elements from the Set:
mySet.clear();
Set also has an iterable interface, which allows you to iterate through its contents using for...of loops or forEach. For example:
for (let value of mySet) {
console.log(value);
}
mySet.forEach(function(value) {
console.log(value);
});
Set can contain different types of data, including numbers, strings, objects and so on. Additionally, it supports strict identity checking of values, which means that object elements will not be considered the same, even if they have the same properties or values.
let obj1 = {name: "John"};
let obj2 = {name: "John"};
mySet.add(obj1);
mySet.add(obj2);
mySet.size; // 2, as obj1 and obj2 are considered different objects
Set in JavaScript is a very useful data structure, especially in cases where you need to store a collection of unique values or check if a certain value exists in the set. It provides convenient methods for working with these values and allows for efficient solution of various tasks.