Set, WeakSet

박민형·2022년 5월 27일
0
post-thumbnail

📌 Set

🔎 개념

👉 중복없이 유일한 값을 저장하려고 할때 사용하는 객체
👉 객체에 찾으려는 값이 존재하는지 체크할 때 유용

  let mySet = new Set();

  mySet.add("crong")
  mySet.add("hary")
  mySet.add("crong")

  // true(set에서 crong이 있는지 없는지 check 해서 boolean 값 반환)
  console.log(mySet.has("crong"));

  // crong, hary(2개만 출력됨 => set은 중복허용 x)
  mySet.forEach((item) => console.log(item));

  // mySet에서 crong item 삭제
  mySet.delete("crong");

📌 WeakSet

🔎 개념

👉 Set과 달리 참조를 가지고 있는 객체만 저장 가능
👉 객체들을 중복없이 저장하려고 할 때 유용

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(111); // 참조를 가지고 있는 객체가 아니라서 오류
ws.add("111"); // 참조를 가지고 있는 객체가 아니라서 오류
ws.add(arr2);
ws.add(obj);

arr = null;

// WeakSet {Array(4), {…}, Array(4)}
// arr을 null로 초기화 했지만 item을 저장하고 있는 것처럼 보임
console.log(ws);
// false true
// 값을 저장하는 것처럼 보이지만 유효하지 않는 객체로 취급(가비지 컬렉션)
// 더 이상 arr은 보관하지 않겠다!!!
console.log(ws.has(arr), ws.has(arr2));

0개의 댓글