Quiz

What are `Set`s and `Map`s and how are they used?

Topics
JavaScript
在GitHub上编辑

TL;DR

Sets and Maps 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. Sets are useful for storing unique items, and Maps are useful for associating values with keys.

// Set example
let mySet = new Set([1, 2, 3, 3]);
mySet.add(4); // Set {1, 2, 3, 4}
// Map example
let myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
console.log(myMap.get('key1')); // 'value1'

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:

let mySet = new Set([1, 2, 3, 3]);
console.log(mySet); // Set {1, 2, 3}

Common methods

  • add(value): Adds a new element with the given value to the Set.
  • delete(value): Removes the element associated with the value.
  • has(value): Returns a boolean indicating whether the value exists in the Set.
  • clear(): Removes all elements from the Set.
  • size: Returns the number of elements in the Set.

Example usage

let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // Duplicate value, will not be added
console.log(mySet.has(1)); // true
console.log(mySet.size); // 2
mySet.delete(1);
console.log(mySet.has(1)); // false
mySet.clear();
console.log(mySet.size); // 0

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:

let myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');

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 the Map.
  • clear(): Removes all elements from the Map.
  • size: Returns the number of elements in the Map.

Example usage

let myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
console.log(myMap.get('key1')); // 'value1'
console.log(myMap.has('key2')); // true
console.log(myMap.size); // 2
myMap.delete('key1');
console.log(myMap.has('key1')); // false
myMap.clear();
console.log(myMap.size); // 0

Further reading

在GitHub上编辑