What are `Set`s and `Map`s and how are they used?
Topics
JavaScript
在GitHub上编辑
TL;DR
Set
s and Map
s are built-in JavaScript objects that help manage collections of data. A Set
is a collection of unique values, while a Map
is a collection of key-value pairs where keys can be of any type. Set
s are useful for storing unique items, and Map
s are useful for associating values with keys.
Set
What is a Set
?
A Set
is a collection of values where each value must be unique. It is similar to an array but does not allow duplicate values.
How to create a Set
You can create a Set
using the Set
constructor:
Common methods
add(value)
: Adds a new element with the given value to theSet
.delete(value)
: Removes the element associated with the value.has(value)
: Returns a boolean indicating whether the value exists in theSet
.clear()
: Removes all elements from theSet
.size
: Returns the number of elements in theSet
.
Example usage
Map
What is a Map
?
A Map
is a collection of key-value pairs where keys can be of any type, including objects, functions, and primitives.
How to create a Map
You can create a Map
using the Map
constructor:
Common methods
set(key, value)
: Adds or updates an element with the specified key and value.get(key)
: Returns the value associated with the key.delete(key)
: Removes the element associated with the key.has(key)
: Returns a boolean indicating whether the key exists in theMap
.clear()
: Removes all elements from theMap
.size
: Returns the number of elements in theMap
.