set
: 자바스크립트의 데이터 타입의 확장 개념 집합데이터를 다룰수 있는 객체
- 중복 데이터 허용X : 중복데이터가 들어오면 체크 후 하나만 남김
- set() : 파라미터는 주로 배열을 사용
- 배열의 index, value 값을 활용하여 집합 데이터를 만듬
- set 전용 메서드들이 있음
- getter,setter가 없기때문에 forEach를 이용해 접근해야함
set 객체 생성 및 초기화
new set( )
new set( array )
예) const testSet = new Set(['html', 'css', 'js']);
사용예시
- 로또번호 생성 : https://jungeun980906.tistory.com/215
set.add( value ) 데이터 추가
<script>
const testSet = new Set(['html', 'css', 'js']);
testSet.add('react'); //Set(4) {'html', 'css', 'js', 'react'}
console.log(testSet);
</script>
set.delete ( value ) 데이터 삭제
<script>
const testSet = new Set(['html', 'css', 'js']);
testSet.delete('html'); //Set(2) {'css', 'js'}
console.log(testSet);
</script>
set.has( value ) 데이터의 존재여부를 true / false로 리턴
<script>
const testSet = new Set(['css', 'js']);
console.log(testSet.has('html')); //false
console.log(testSet.has('css')); //true
</script>
set.foeEach(callback function) set 순환
testSet.forEach(function(value,index,self){
console.log(index,value,self);
}); // value와 index가 동일
set.entries() / set.keys() key에 접근 / set.values value에 접근
- 리턴타입은 SetIterator : 별도의 메서드를 사용하여 접근해야함
- SetIterator : set의 상위 인터페이스 규격
- keys() 와 values()의 값은 동일
1. entries() : 내부 타입에 접근하여 pair의 값을 가져옴 (key와 value)
console.log(testSet.entries());
for(const iter of testSet.entries()){
//iter = testSet의 key,value값 (속성=배열)
console.log(iter); //배열로 출력됨
}
for(const iter of testSet.entries()){
iter.forEach(function(v, i, s){ //하나씩 출력됨
console.log(i, v);
})
}
2. keys() : 식별자로 사용하는 값을 리턴
console.log(testSet.keys());
for(const k of testSet.keys()){
console.log(k);
}
3. values() : 내부값을 리턴
console.log(testSet.values());
for(const v of testSet.values()){
console.log(v);
}
iterable : 반복이 가능함을 의미
반복이 가능한 요소 : 배열, map, set, iterable한 요소(list, set, map)
=> for of / spread 문법 사용 가능
for in : 객체의 모든 열거가 가능한 속성에 대한 반복
for of : [Simbol.iterator] 속성을 가지는 컬렉션에 적용
- iterator은 for과 forEach보다 상위 개념
set.size set의 개수
- 괄호 ( ) 없음!
<script>
const testSet = new Set(['html', 'css', 'js']);
console.log(testSet.size); //3
</script>
set.clear() set비우기
testSet.clear(); // set비우기
console.log(testSet); // 아무것도 출력되지 않음
console.log(testSet.size); // 0
사용 팁!
1. set의 마지막 번지에 있는 값을 꺼내고 싶은 경우
- set을 배열[ ]로 변경한 뒤 : forEach를 돌려서 배열에 push로 넣던가 for of를 사용하여 push로 넣기
- pop()으로 마지막 값을 가져와야함
//배열로 변경
let Arr = [ ];
Set.forEach(function(keys){
Arr.push(keys);
});
//보너스 번호
let Number = Arr.pop();
'JS > JS 공부' 카테고리의 다른 글
[JS] class, 객체, 생성자 (0) | 2023.04.18 |
---|---|
[JS] try~catch 예외 처리 (0) | 2023.04.18 |
[JS] Map (0) | 2023.04.18 |
[JS] 새로고침, 취소 location.reload (0) | 2023.04.18 |
[JS] 데이터 구조화 (0) | 2023.04.17 |