
자료 구조중 하나로 데이터 집합체다. Set의 값은 한번만 나타날 수 있으며 고유한 값이다.
const set =new Set([1,2,3]);
console.log(set); // Set(3) { 1, 2, 3 }
Set 객체에 있는 값의 수를 반환
const set =new Set([1,2,3]);
console.log(set); // Set(3) { 1, 2, 3 }
console.log(set.size); // 3
Set 객체에 특정값을 가진 새 요소 추가
const set =new Set([1,2,3]);
set.add(4);
console.log(set); //Set(4) { 1, 2, 3, 4 }
set.add(3); // Set은 중복이 안된다.
console.log(set); // Set(4) { 1, 2, 3, 4 }
Set 객체에 해당하는 요소를 제거
const set =new Set([1,2,3]);
set.add(4);
console.log(set); //Set(4) { 1, 2, 3, 4 }
console.log(set.delete(4)); // true
console.log(set);// Set(3) { 1, 2, 3 }
Set 객체에서 모든 요소 제거
const set =new Set([1,2,3]);
console.log(set); // Set(3) { 1, 2, 3 }
set.clear();
console.log(set); // Set(0) {}
주어진 값을 가진 요소가 Set 객체에 있는지 여부를 나타내는 Boolean 반환
const set =new Set([1,2,3]);
console.log(set); // Set(3) { 1, 2, 3 }
console.log(set.has(3)); // true
Iteration protocol을 구현하며 Set의 값을 산출하는 반복자를 반환한다.
const odds=new Set([1,3,5,7,9]);
const iterator = odds[Symbol.iterator]();
console.log(iterator.next());
// { value: 1, done: false }
console.log(iterator.next());
//{ value: 3, done: false }
Set은 배열을 인자로 받기 때문에 iterable하다고 할 수 있다.
따라서 iterable객체의 메소드인 keys(), values(), entries() 사용 가능하다.
const set =new Set([1,2,3]);
console.log(set.values()); //[Set Iterator] { 1, 2, 3 }
console.log(set.keys()); // [Set Iterator] { 1, 2, 3 }
console.log(set.entries());
// [Set Entries] { [ 1, 1 ], [ 2, 2 ], [ 3, 3 ] }
for..of 연산자 사용 가능하다.
const set =new Set([1,2,3]);
for(const value of set){
console.log(value); // 1 2 3
}
forEach() 고차함수도 사용 가능하다.
const set =new Set([1,2,3]);
set.forEach(item => console.log(item)); // 1 2 3
const arr =[1,2,3,4,4,1];
const set =new Set([...arr]);
console.log(set); //Set(4) { 1, 2, 3, 4 }
const set1 = new Set([1,2,3,4]);
const set2 = new Set([3,4,5,6]);
const newSet1= [...set1].filter(item => set2.has(item));
console.log(new Set(newSet1)); // Set(2) { 3, 4 }