LEARNING JAVASCRIPT - Trang 188

userRoles

.

set

(

u1

,

'User'

);

userRoles

.

set

(

u2

,

'User'

);

userRoles

.

set

(

u3

,

'Admin'

);

// poor James...we don't assign him a role

The

set()

method is also chainable, which can save some typing:

userRoles

.

set

(

u1

,

'User'

)

.

set

(

u2

,

'User'

)

.

set

(

u3

,

'Admin'

);

You can also pass an array of arrays to the constructor:

const

userRoles

=

new

Map

([

[

u1

,

'User'

],

[

u2

,

'User'

],

[

u3

,

'Admin'

],

]);

Now if we want to determine what role

u2

has, you can use the

get()

method:

userRoles

.

get

(

u2

);

// "User"

If you call

get

on a key that isn’t in the map, it will return

undefined

. Also, you can

use the

has()

method to determine if a map contains a given key:

userRoles

.

has

(

u1

);

// true

userRoles

.

get

(

u1

);

// "User"

userRoles

.

has

(

u4

);

// false

userRoles

.

get

(

u4

);

// undefined

If you call

set()

on a key that’s already in the map, its value will be replaced:

userRoles

.

get

(

u1

);

// 'User'

userRoles

.

set

(

u1

,

'Admin'

);

userRoles

.

get

(

u1

);

// 'Admin'

The

size

property will return the number of entries in the map:

userRoles

.

size

;

// 3

Use the

keys()

method to get the keys in a map,

values()

to return the values, and

entries()

to get the entries as arrays where the first element is the key and the sec‐

ond is the value. All of these methods return an iterable object, which can be iterated

over by a

for...of

loop:

for

(

let

u

of

userRoles

.

keys

())

console

.

log

(

u

.

name

);

for

(

let

r

of

userRoles

.

values

())

console

.

log

(

r

);

for

(

let

ur

of

userRoles

.

entries

())

console.log(

`

${

ur

[

0

].

name

}

:

${

ur

[

1

]

}

`

);

164 | Chapter 10: Maps and Sets

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.