chapter10. 맵과 셋

10.1 맵

ES6 이전에는 키와 값을 연결하려면 객체를 사용해야함, 여러 단점 생성

  • 프로토타입 체인으로 인해 의도하지 않은 연결이 생길 수 있음
  • 객체 안에 연결된 키와 값이 몇 개인지 쉽게 알수 없음
  • 키는 반드시 문자열이나 심볼이여야 하므로 객체를 키로 써서 값과 연결할 수 없음
  • 객체는 프로퍼티 순서를 보장하지 않음
map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//map
const u1= {name : 'Cynthia'};
const u2= {name : 'Jackson'};
const u3= {name : 'Olive'};
const u4= {name : 'James'};

const userRoles = new Map(); //맵 생성

//set()을 사용해 사용자 역할 할당
//set()은 체인으로 연결 할 수 있음
userRoles
.set(u1,'User')
.set(u2,'User')
.set(u3,'Admin');

//생성자에 배열의 배열을 넘기는 형태로 써도됨
const userRoles = new Map([
[u1,'User'],
[u2,'User'],
[u3,'Admin'],
]);

//u2의 role은? get();
userRoles.get(u2); //"User"

맵에 존재하지 않은 키에 get()을 호출하면 undefined를 반환
has() : 맵에 키가 존재하는지 확인

get&has
1
2
3
4
5
//get()과 has()
userRoles.has(u1)//true
userRoles.get(u1) //"User"
userRoles.has(u4) //false
userRoles.get(u4) //undefined

맵에 이미 존재하는 키에 set()을 호출하면 값이 교체

set()으로값교체
1
2
3
4
//set()으로 값 교체
userRoles.get(u1); //"User"
userRoles.set(u1,"Admin");
userRoles.get(u1); //"Admin"

size : 맵의 요소 숫자를 반환

size
1
userRoles.size; //3

keys() : 맵의 키
value() : 값
entries() : 첫번째 요소가 키이고 두번째 요소가 값인 배열 반환

  • 모두 for…of 루프를 사용할 수 있다.
keys,value,entries
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
for(let u of userRoles.keys())
console.log(u.name);

/*
Cynthia
Jackson
Olive
*/


for(let r of userRoles.values())
console.log(r);

/*
Admin
User
Admin
*/

for(let ur of userRoles.entries())
console.log(`${ur[0].name}:${ur[1]}`);
/*
Cynthia:Admin
Jackson:User
Olive:Admin
*/

//맵도 분해 가능
for(let [u,r] of userRoles.entries())
console.log(`${u.name}:${r}`);

/*
Cynthia:Admin
Jackson:User
Olive:Admin
*/

//entries() 메서드는 맵의 기본 이터레이터
//단축 가능합니다.
for(let[u,r] of userRoles)
console.log(`${u.name}:${r}`);

/*
Cynthia:Admin
Jackson:User
Olive:Admin
*/

delete() : 맵의 요소를 지움

delete()
1
2
3
//delete() :맵의 요소를 지움
userRoles.delete(u2);
userRoles.size //2

clear() : 맵의 모든 요소를 지움

clear()
1
2
3
//clear() : 맵의 모든 요소를 지움
userRoles.clear();
userRoles.size //0

10.2 위크맵

WeakMap은 다음 차이점을 제외하면 Map과 완전히 같다.

  • 키는 반드시 객체여야한다.
  • WeakMap의 키는 가비지 콜렉션에 포함 될 수 있다.
  • WeakMap은 이터러블이 아니며 clear() 메서드도 없다.
  • 자바스크립트 코드는 코드 어디에서 객체를 참조하는한 객체를 메모리에서 계속 유지
  • WeakMap은 그렇지 않으므로, 객체 인스턴스의 전용(private)한 키를 저장하기에 알맞는다.
WeakMap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//WeakMap
const SecretHolder = (function(){
const secrets = new WeakMap();
return class{
setSecret(secret){ //비밀저장
secrets.set(this, secret);
}
getSecret(){ //비밀호출
return secrets.get(this);
}
}
})();
const a = new SecretHolder();
const b = new SecretHolder();

a.setSecret('secret A');
b.setSecret('secret B');

a.getSecret(); //secret A
IIEF 내부에서 그 인스턴스의 비밀스러운 내용을 저장할 수 있는 SecretHolder
클래스를 얻게된다.

10.3 셋

Set() : 중복을 허용하지 않는 데이터 집합ㅊ

set()
1
2
3
4
5
6
7
8
9
10
11
12
const roles = new Set();
roles.add("User"); //사용자 역할 추가 add();
roles.add("Admin"); //관리자 역할 추가 add();

/*
Set(2) {"User", "Admin"}
*/
roles.size; //2

roles.delete("User"); //true
roles //Set(1) {"Admin"}
roles.delete("User"); //false

10.3 위크셋

WeakSet() : 객체만 포함 할 수 있으며, 이 객체들은 가비지 콜렉션의 대상이됨

  • 이터러블이 아님
  • 주어진 객체가 set 안에 존재하는지 아닌지 판단하는 정도
WeakSet()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const naughty = new WeakSet();
const childen = [
{name:'Suzy'},
{name : 'Derek'},
];

naughty.add(childen[1]); //value: {name: "Derek"}

for(let child of childen){
if(naughty.has(child))
console.log(`Coal for ${child.name}`)
else
console.log(`presents for ${child.name}`)
}
/*
presents for Suzy
Coal for Derek
*/
# map, set

Comentarios

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×