일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- built in object
- HTML
- solidity
- Props
- nextJS
- middleware
- evm
- hardhat
- CSS
- Interface
- tailwindcss
- REACT
- Ethereum
- Redux
- blockchain
- graphQL
- concept
- error
- node.js
- typeScript
- express.js
- bitcoin
- 기준
- 삶
- web
- API
- useState
- SSR
- JavaScript
- CLASS
- Today
- Total
ReasonJun
javascript : set 본문
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.
'Frontend > Javasciprt' 카테고리의 다른 글
javascript : symbol (0) | 2023.06.09 |
---|---|
javascript : map (0) | 2023.06.09 |
javascript : event (mouse pointer event, prevent basic work) (0) | 2023.06.09 |
javascript : event (handler once, passive, keyboard) (0) | 2023.06.09 |
javascript : event (event obj, focus form event) (0) | 2023.06.09 |