ReasonJun

javascript : set 본문

Frontend/Javasciprt

javascript : set

ReasonJun 2023. 6. 9. 00:11
728x90

set

In JavaScript, a Set is a built-in data structure that allows you to store unique values of any type. It provides a way to store a collection of values without any duplicates. The values in a Set can be of any type, including primitives like numbers and strings, as well as objects and other sets.

const mySet = new Set(); // creating a new Set
const mySet = new Set([1, 2, 3, 3, 4, 5, 5]); // initialize a Set

In this example, the Set will only contain the unique values from the array [1, 2, 3, 3, 4, 5, 5], namely 1, 2, 3, 4, 5.

Sets have several useful methods to manipulate and retrieve values. Here are some commonly used methods:

  • add(value): Adds a new value to the Set. If the value already exists, it will be ignored.
  • delete(value): Removes a value from the Set. Returns true if the value was present and removed, or false if it was not found.
  • has(value): Checks if a value exists in the Set. Returns true if the value is found, or false otherwise.
  • size: Returns the number of elements in the Set.
  • clear(): Removes all elements from the Set.
const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(3); // Ignored, already exists
console.log(mySet.size); // Output: 3

console.log(mySet.has(2)); // Output: true

mySet.delete(2);
console.log(mySet.has(2)); // Output: false

mySet.clear();
console.log(mySet.size); // Output: 0

You can also iterate over the values in a Set using the forEach method or by using a for...of loop:

mySet.forEach(value => {
  console.log(value);
});

for (const value of mySet) {
  console.log(value);
}

Sets are useful when you need to store a collection of unique values and quickly check for the existence of a particular value. They provide an efficient way to handle sets of data without writing complex logic to manage uniqueness manually.

728x90
Comments