JavaScript - 14

Doodream·2021년 4월 30일
0

코어 자바스크립트

목록 보기
18/36
post-thumbnail

Set

객체로서 iterable 한 자료형이다. 생성시 배열을 생성자 인수로 받으며 받은 배열의 원소들을 중복되지 않게 받아들인다. 즉, 생성시 자동으로 중복이 걸러지는 것이다.

  • 중복된 값을 아무리 많이 add하여도 걸러 추가한다.

let testSet = new Set([1, 2, 3, 4, 5, 1, 2, 3]);
console.log(testSet.size);
console.log(testSet.has(1));
console.log(testSet.has(7));
//add
testSet.add(6);
testSet.add(6);
console.log(testSet);
//delete
testSet.delete(4);
console.log(testSet);
// clear
testSet.clear();
console.log(testSet);
testSet = new Set([1, 2, 3, 4, 5, 1, 2, 3]);
for (const num of testSet) console.log(num);

Map

객체로서 key 와 value가 존재한다. 하지만 이 자료형은 같은 키에는 한가지 value만을 대응하기 위해서 존재한다. 이렇게 한쌍이 존재한다.

그런데 그런면에서는 객체와 비슷할지 모른다. 하지만

  • 객체의 키값은 무조건 문자열이다. 하지만 Map의 키값은 무엇이든 될 수 있다.

  • 다만 키값은 실제 객체를 생성하면서 넣으면 같은 값을 같더라도 callstack에는 같은 주소를 가르키지않기 때문에( 사실상 다른 객체) 주의하며 넣어야한다.

  • 마찬가지로 iterable한 자료형이므로 spread 문법이 가능하며 Set이나 Map을 array 로 형변환이 가능하다.

const testMap = new Map();
testMap
  .set(1, 'one')
  .set(2, 'two')
  .set(document.querySelector(`h1`), `Heading`);
console.log(testMap); // Map(3) {1 => "one", 2 => "two", h1 => "Heading"}
console.log(testMap.has(1)); // true
console.log(testMap.get(2)); // two
console.log(testMap.get(10)); // undefined
testMap.delete(2); 
console.log(testMap); // Map(2) {1 => "one", h1 => "Heading"}
console.log(testMap.size); // 2
console.log([...testMap]); // Map → array
/* (2) [Array(2), Array(2)]
0: (2) [1, "one"]
1: (2) [h1, "Heading"]
length: 2
__proto__: Array(0)*/

💡 Set과 Map은 둘다 객체형태이며 iterable하기 때문에 공통점이 있다.

  • .entries() // Set은 key와 value값이 같다.
  • .values()
  • .keys()
  • Spread 사용가능
  • for of 구문 사용가능

❗️ Object.entries(Set || Map) !== (Set || Map).entries()
코드가 의미하는 바와 같이 둘은 엄연히 다르다. 좌단은 배열을 반환하며 우단은 Set 혹은 Map의 Iterator를 반환한다.

  • Object.entries는 일반객체, 문자열이 사용가능하다.[key,value] 반환
  • .entries()Set, Map, Array 사용가능하다. iterable 객체 반환
  • entries, values, keys 전부 위의 개념이 적용된다.
const testSet = new Set([1, 2, 3, 4, 5, 1, 2, 3]);
console.log(testSet.entries()); 
// SetIterator {1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5}
console.log(testSet.values());
// SetIterator {1, 2, 3, 4, 5}
console.log(testSet.keys());
// SetIterator {1, 2, 3, 4, 5}
const testMap = new Map();
testMap
  .set(1, 'one')
  .set(2, 'two')
  .set(document.querySelector(`h1`), `Heading`);
console.log(testMap.entries());
// MapIterator {1 => "one", h1 => "Heading"}
console.log(testMap.keys());
// MapIterator {1, h1}
console.log(testMap.values());
// MapIterator {"one", "Heading"}
profile
일상을 기록하는 삶을 사는 개발자 ✒️ #front_end 💻

0개의 댓글