
알고있으면 좋은 Javascript Tip✨
Set()
- Set 객체는 중복되지 않는 유일한 값들의 집합이다.
- 쉽게 말해, 동일한 값을 중복하여 포함할 수 없고, 요소 순서에 의미가 없으며, 인덱스로 요소 접근이 불가능하다.
(1) Set 객체 생성하기
- Set 생성자 함수로 생성하며, 인수를 전달하지 않으면 빈 Set 객체가 생성된다.
const example = new Set();
// Set(0) {}
console.log(example);
- 중복된 값은 Set 객체에 요소로 저장되지 않으므로, 배열에서 중복된 요소를 제거하는데 사용한다.
const example1 = new Set([1, 2, 3, 3]);
console.log(example1); // Set(3) {1, 2, 3}
const example2 = new Set('hello');
console.log(example2); // Set(4) {"h", "e", "l", "o"}
// Set을 사용한 배열의 중복 요소 제거
const uniq = array => [...new Set(array)];
console.log(uniq([2, 1, 2, 3, 4, 3, 4])); // [2, 1, 3, 4]
(2) Set 객체 사용하여 요소 개수 확인하기
- Set 객체의 요소 개수를 확인하고 싶다면 Set.prototype.size 프로퍼티를 사용하면 된다.
// size 프로퍼티는 getter 함수만 존재하는 접근자 프로퍼티
const { size } = new Set([1, 2, 3, 3]);
// 3
console.log(size);
const example = new Set([1, 2, 3]);
console.log(Object.getOwnPropertyDescriptor(Set.prototype, 'size'));
// {set: undefined, enumerable: false, configurable: true, get: ƒ}
// size 프로퍼티에 숫자를 할당해서 size 개수를 변경하려는 시도는 무시된다.
example.size = 10;
// 3
console.log(example.size);
(3) Set 객체 사용하여 요소 추가하기
- Set 객체에 요소를 추가하려면 Set.prototype.add 메서드를 사용하면 된다.
const example = new Set();
// Set(0) {}
console.log(example);
// add 메서드는 새로운 요소가 추가된 Set 객체를 반환한다.
example.add(1);
// Set(1) {1}
console.log(example);
// 메서드 체이닝이 가능하다.
const example = new Set();
example.add(1).add(2);
// Set(2) {1, 2}
console.log(example);
// 중복된 요소 추가는 허용하지 않는다.
const example = new Set();
example.add(1).add(2).add(2);
// Set(2) {1, 2}
console.log(example);
(4) Set 객체 사용하여 요소 존재 여부 확인하기
- Set 객체에서 특정 요소의 존재 여부를 확인해 보려면 Set.prototype.has 메서드를 사용하면 된다.
const example = new Set([1, 2, 3]);
console.log(example.has(2)); // true
console.log(example.has(4)); // false
(5) Set 객체 사용하여 요소 삭제하기
- Set 객체에서 특정 요소를 삭제하려면 Set.prototype.delete 메서드를 사용하면 된다.
- delete 메서드에는 인덱스가 아닌 삭제하려는 요소 값을 인수로 전달해야 한다.
const example = new Set([1, 2, 3]);
// 요소 2를 삭제한다.
example.delete(2);
// Set(2) {1, 3}
console.log(example);
// 요소 1을 삭제한다.
example.delete(1);
// Set(1) {3}
console.log(example);
// 마찬가지로 메서드 체이닝이 가능하다.
const example = new Set([1, 2, 3]);
// delete는 불리언 값을 반환한다.
example.delete(1).delete(2);
(6) Set 객체 사용하여 요소 일괄 삭제하
- Set 객체의 모든 요소들을 일괄 삭제하고 싶다면 Set.prototype.clear 메서드를 사용하면 된다.
const example = new Set([1, 2, 3]);
example.clear();
// Set(0) {}
console.log(example);'Study > JavaScript' 카테고리의 다른 글
| [JS] reduce (0) | 2023.10.17 |
|---|---|
| [JS] call & apply & bind (0) | 2023.10.05 |
| [JS] 이벤트 루프 (0) | 2023.09.07 |
| [JS] this (0) | 2023.09.07 |
| [JS] 현재 날짜, 시간 가져오기 (0) | 2023.09.07 |