- 중복되지 않는 유일한 값들의 집합
- 요소에 순서가 없다.
- 인덱스로 요소에 접근할 수 없다.
Set 객체 생성
const set1 = new Set();
console.log(set); // Set(0) {}
const set2 = new Set([1, 2, 3, 3]);
console.log(set); // Set(3) {1, 2, 3}
const set3 = new Set('hello');
console.log(set); // Set(4) {"h", "e", "l", "o"}
//중복 제거
const uniq = array => array.filter((v, i, self) => self.indexOf(v) === i);
const uniq = array => [ ... new Set(array)];
// 두 코드 실행 시 동일한 결과 출력
console.log(uniq([2, 1, 2, 3, 4, 3, 4]); // [2, 1, 3, 4]
요소 개수 확인
Set.prototype.size 프로퍼티 사용
const { size } = new Set([1, 2, 3, 3]);
const set = new Set([1, 2, 3]);
set.size = 10; // 무시(변경 불가)
console.log(set.size); // 3
- size 프로퍼티는
setter 함수 없이 getter 함수만 존재
요소 추가
const set = new Set();
set.add(1);
console.log(set); // Set(1) {1}
//연속적 호출 가능
set.add(1).add(2);
console.log(set); // Set(3) {1, 2}
//중복된 요소 추가 무시
set.add(1).add(2).add(2);
console.log(set); // Set(2) {1, 2}
set.add(NaN).add(NaN); // 중복 추가 무시
set.add(0).add(-0); // 중복 추가 무시
console.log(set); // Set(2) {NaN, 0}
=== 연산자는 NaN을 다르다고 평가
Set 객체는 NaN을 같다고 평가
const set = new Set();
set
.add(1)
.add('a')
.add(true)
.add(undefined)
.add(null)
.add({})
.add([])
.add(() => {});
console.log(set);
// Set(8) {1, "a", true, undefined, null, {}, [], () => {}}
요소 존재 여부 확인