Set으로 유니크한 배열 만들기
: 중복없이 유일한 값을 저장하려고 할때, 이미 존재하는지 체크할 때 유용
let mySet = new Set();
// 자료형
console.log(toString.call(mySet));
>> "[object Set]"
// set에 인자 추가
mySet.add("crong");
mySet.add("hary");
mySet.add("crong");
// 해당 요소가 있는지 불린값 반환
console.log(mySet.has("crong"));
>> true
// 요소 삭제
mySet.delete("crong");
// 요소 하나씩 출력
mySet.forEach(function(v){
console.log(v);
})
>> "hary"
WeakSet
: 참조를 가지고 있는 객체만 저장 가능, 객체 형태를 중복 없이 저장하려고 할 때 유용
let arr = [1,2,3,4];
let arr2 = [5,6,7,8];
let obj = {arr, arr2};
let ws = new WeakSet();
ws.add(arr);
ws.add(function(){});
ws.add(111); // -> error
ws.add('abcd'); // -> error
ws.add(null); // -> error
ws.add(arr2);
ws.add(obj);
arr = null;
console.log(ws); // -> arr 삭제
Map & WeakMap 추가정보를 담은 객체저장하기
map & weakmap
array -> set, weakset
object -> map, weakmap
map은 key, value 구조
let wm = new WeakMap();
let myfun = function(){};
//이 함수가 얼마나 실행됐지?를 알려고 할 때
wm.set(myfun,0);
let count = 0;
for(let i=0; i<10;i++){
count = wm.get(myfun); //get value
count++;
wm.set(myfun, count);
}
console.log(wm);
>> WeakMap {ƒ => 10}
WeakMap 클래스 인스턴스 변수 보호하기
function Area(height, width){
this.height = height;
this.width = width;
}
Area.prototype.getArea = function(){
return this.height * this.width;
}
let myarea = new Area(10,20);
console.log(myarea.getArea());
console.log(myarea.height);
>> 200
>> 10
//WeakMap 활용
const wm = new WeakMap();
function Area(height, width){
wm.set(this, {height, width});
}
Area.prototype.getArea = function(){
const {height, width} = wm.get(this);
return height * width;
}
let myarea = new Area(10,20);
console.log(myarea.getArea());
console.log(myarea.height);
>> 200
>> undefined
'JSTS' 카테고리의 다른 글
[JS][ES6] Arrow function, defualt parameter, rest parameter (0) | 2022.06.05 |
---|---|
[JS][ES6] Template 처리 (0) | 2022.06.05 |
[JS][ES6] 객체, destructuring (0) | 2022.06.05 |
[JS][ES6] string, for of, from, spread (0) | 2022.06.05 |
[JS][ES6] const, let (0) | 2022.06.05 |