LEARNING JAVASCRIPT - Trang 191

To remove a role, we simply call

delete()

, which returns

true

if the role was in the

set and

false

otherwise:

roles

.

delete

(

"Admin"

);

// true

roles

;

// Set [ "User" ]

roles

.

delete

(

"Admin"

);

// false

Weak Sets

Weak sets can only contain objects, and the objects they contain may be garbage-

collected. As with

WeakMap

, the values in a

WeakSet

can’t be iterated, making weak sets

very rare; there aren’t many use cases for them. As a matter of fact, the only use for

weak sets is determining whether or not a given object is in a set or not.
For example, Santa Claus might have a

WeakSet

called

naughty

so he can determine

who to deliver the coal to:

const

naughty

=

new

WeakSet

();

const

children

=

[

{

name

:

"Suzy"

},

{

name

:

"Derek"

},

];

naughty

.

add

(

children

[

1

]);

for

(

let

child

of

children

) {

if

(

naughty

.

has

(

child

))

console.log(

`Coal for

${

child

.

name

}

!`

);

else

console.log(

`Presents for

${

child

.

name

}

!`

);

}

Breaking the Object Habit

If you’re an experienced JavaScript programmer who’s new to ES6, chances are

objects are your go-to choice for mapping. And no doubt you’ve learned all of the

tricks to avoiding the pitfalls of objects as maps. But now you have real maps, and you

should use them! Likewise, you’re probably accustomed to using objects with boolean

values as sets, and you don’t have to do that anymore, either. When you find yourself

creating an object, stop and ask yourself, “Am I using this object only to create a

map?” If the answer is “Yes,” consider using a

Map

instead.

Weak Sets | 167

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.