[JavaScript] Set 객체란?
Set 객체는 자바스크립트의 표준 내장 객체 중 하나이다.
1. Set 객체
Set 객체는 유일한 값들을 저장하는 콜렉션(Collection)이다. 즉, 중복된 값이 존재하지 않는다.
또한 Set 객체의 값은 어떠한 자료형(Data-type)에도 구애받지 않는다.
2. Set 객체 메서드
Set 객체를 사용할 때 자주 쓰이는 메서드 5가지를 소개한다.
1) new Set()
새로운 Set 객체를 생성한다.
const arr = [1, 2, 3, 3, 4, 5, 5];
const set = new Set(arr);
// 3 ways to convert a set to an array
// 1) using Array.from()
const newArr = Array.from(set);
// 2) using spread operator
// const newArr = [...set];
// 3) using forEach()
// const newArr = [];
// set.forEach((e) => {
// newArr.push(e);
// })
console.log(arr);
console.log(newArr);
// Expected Output:
// [1, 2, 3, 3, 4, 5, 5]
// [1, 2, 3, 4, 5]
Set 객체의 값을 확인하기 위해서는 배열로 변환 후 확인이 가능하다.
2) add()
Set 객체에 새로운 요소를 추가한다.
const set = new Set();
set.add(1);
set.add(2);
set.add(3);
const arr = [...set];
console.log(arr);
// Expected Output:
// [1, 2, 3]
3) delete()
Set 객체에 한 요소를 제거한다.
const set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.delete(3);
const arr = [...set];
console.log(arr);
// Expected Output:
// [1, 2]
4) has()
Set 객체에 특정 값의 유무를 판별한다.
const set = new Set();
set.add(1);
set.add(2);
set.add(3);
console.log(set.has(1));
console.log(set.has(5));
// Expected Output:
// true
// false
5) clear()
Set 객체에 모든 요소를 제거한다.
const set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.clear();
console.log(set.size);
// Expected Output:
// 0
size는 Set 객체에 저장된 요소의 개수를 반환한다.
Leave a comment