Set 과 Map

이재영·2023년 4월 6일
0

HTML CSS JS

목록 보기
20/22

Set

Set은 배열에 중복되지않는 값을 저장할 수 있다.
배열은 요소에 순서에 의미가 있는데 set은 없다.
배열은 인덱스로 접근을 하는데 set은 접근이 안된다.
값으로만 이루어져있고 중복값은 허용하지 않는다.

const s = new Set();

//요소를 추가하는 방법
//메서드를 사용해서

s.add("one");
s.add("one");
//중복값은 허용하지 않는다.
s.add("two");
s.add("three");

console.log(s); // 중복을 허용하지 않기 때문에 Set(3) {'one', 'two', 'three'} 출력된다.
const arr =[1,2,3,4,5];

const ss = new Set(arr);
console.log(ss); // Set(5) {1, 2, 3, 4, 5} 출력된다.

//has : 값이 가지고 있는지 확인하는 메서드
console.log(ss.has(2)); // true 출력
console.log(ss.has(6)); // false 출력

//delete : 하나의 요소를 제거하는 메서드
ss.delete(2);
console.log(ss); // Set(4) {1, 3, 4, 5} 출력된다.

//clear : 모든 값을 제거하는 메서드
ss.clear();
console.log(ss); // Set(0) {size: 0} 출력된다.

Map

키와 벨류를 한쌍으로 저장하고 중복된 키값을 허용하지 않는다.
iterator를 통해 Map 객체 내부를 순회할 수 있다.

Map은 값을 추가할 때 키와 같이 한쌍으로 추가해줘야한다.
set 메소드를 통해 값을 저장
키를 왜 저장할까 ? 키로 저장된 값을 호출하기 위해

const map = new Map();

map.set("one",1);
map.set("one",2);
map.set("two",2);
map.set("three",3);
console.log(map);

// map은 get이라는 메소드로 값을 호출할 수 있다.
//중복되는 키를 허용하지 않는다. 키값이 겹치면 마지막으로 저장한 값이 뜬다.
console.log(map.get("one"));  // 2가 출력된다.
console.log(map.get("two")); // 2가 출력된다.
//값을 삭제하는법
// delete("매개변수에 삭제할 키값");
map.delete("one");
console.log(map); // Map(2) {'two' => 2, 'three' => 3}

// map의 사이즈 확인 , map의 저장된 요소가 몇개인지
// map 저장된 요소의 갯수를 확인할 수 있다.
console.log(map.size); // 2

//map 에 저장된 키값들을 전부 반환해주는 메서드
const keys = map.keys();
console.log(keys); // MapIterator {'two', 'three'}

//map에 저장된 벨류들을 반환해주는 메서드
const values = map.values();
console.log(values); // MapIterator {2, 3}

//entries() :[키,값]형태의 정보들을 모아서 MapIterator 객체로 변환 반환.

const iter = map.entries();
console.log(iter); // MapIterator {'two' => 2, 'three' => 3}
console.log(iter.next().value); // (2) ['two', 2]


// 키 정보만 출력 시키게 for of 문으로 작성해보자
for(const iterator of keys){
    //이터레이터 요소가 끝날때까지 반복하면서 요소를 보여준다.
    console.log(iterator); // two , three 2줄 출력
}

// 값만 보여주자

for(const iterator of values){
    console.log(iterator); // 2 ,3  2줄 출력
}

// for of문으로 키랑 값을 모두 출력
for(const [key,value] of iter){
    console.log(`키는 ${key}, 값은 ${value}이다`);
  //키는 three, 값은 3이다 한줄 출력된다. 그 이유는 위에서 next로 키 two, 값 2 인 값은 반환되었기 때문에
}

//forEach 문으로 키, 값 모두 출력
map.forEach(function(value,key){
    console.log(`키는 ${key}, 값은 ${value}`);
}) //키는 two, 값은 2 , 키는 three, 값은 3 2줄 출력
profile
한걸음씩

0개의 댓글