国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
What is a Map?
What is a Set?
When to Use Map vs Object
Bonus Tip: WeakMap and WeakSet
Home Web Front-end JS Tutorial What are Map and Set data structures in ES6?

What are Map and Set data structures in ES6?

Jun 24, 2025 am 12:11 AM
es6 data structure

Map and Set are two new data structures introduced by ES6, providing more flexible and efficient key-value pairs and unique value storage methods. 1. Map supports any type of keys, maintains the insertion order, suitable for non-string keys, quick search and avoid attribute conflicts; 2. Set stores unique values, automatically deduplicates, suitable for tracking unique items or array deduplication; 3. When selecting Map instead of object, including the keys being non-string, size required or frequent iterations; 4. WeakMap and WeakSet are used in weak reference scenarios to prevent memory leakage but cannot be iterated or cleared.

What are Map and Set data structures in ES6?

If you're diving into ES6 JavaScript, you've probably come across Map and Set . These are two new built-in data structures introduced in ES6 that offer more flexibility and better performance in certain use cases compared to traditional objects and arrays.


What is a Map?

A Map is a collection of key-value pairs where both the keys and values ??can be of any type — not just strings like with regular JavaScript objects. This makes it especially useful when you need to associate metadata or store information related to DOM elements, functions, or other non-string keys.

Key features of Map:

  • Keys can be any type (including objects, functions, etc.)
  • Maintains insertion order
  • Easily iterable
  • Comes with built-in methods for adding, retrieving, and removing entries
 const myMap = new Map();
myMap.set('name', 'Alice');
myMap.set(42, 'Answer');

console.log(myMap.get(42)); // Output: Answer

You might reach for a Map when:

  • You want to avoid accidental name clashes with default object properties
  • You need fast looksups and deletions
  • You're dealing with keys that aren't strings

What is a Set?

A Set is a collection of unique values. That means no duplicates are allowed — if you try to add the same value twice, only the first occurrence will remain. Like Map , Set also maintains insertion order and is iterable.

Key features of Set:

  • Stores unique values
  • Maintains insertion order
  • Provides easy ways to add, delete, and check for existence
 const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // won't be added again

console.log(mySet); // Output: Set { 1, 2 }

Use a Set when:

  • You want to keep track of unique items
  • You need an efficient way to check if something exists
  • You want to remove duplicates from an array quickly

For example, deduping an array becomes super simple:

 const arr = [1, 2, 2, 3];
const uniqueArr = [...new Set(arr)]; // [1, 2, 3]

When to Use Map vs Object

Although Map looks similar to a regular object, there are practical differences that make one more suitable than the other depending on your needs.

Choose Map if:

  • Your keys aren't strings or numbers
  • You need to know the size of the collection easily ( map.size )
  • You plan to iterate through entries often
  • You're worried about accidentally overwriting built-in object properties

Stick with plain objects if:

  • You don't need advanced features of Map
  • You're working with JSON or APIs that expect plain objects
  • Performance isn't a concern and code simplicity matters more

Also, keep in mind that Map instances aren't as straightforward to serialize (like with JSON.stringify ) as plain objects.


Bonus Tip: WeakMap and WeakSet

ES6 also introduced WeakMap and WeakSet , which are variations of Map and Set . They hold weak references to their keys (in the case of WeakMap ) or values ??(for WeakSet ), meaning they don't prevent garbage collection. These are handy for things like caching private data or associating extra info with DOM nodes without memory leaks.

But unlike Map and Set , WeakMap and WeakSet :

  • Are not iterable
  • Don't have .clear() or .size
  • Only accept objects as keys/values ??(no primitives)

So yeah, Map and Set bring some nice upgrades to JavaScript's data handling game. They're not always necessary, but once you hit a situation where unique or flexible keys matter, they'll feel like a natural fit.

The above is the detailed content of What are Map and Set data structures in ES6?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
Compare complex data structures using Java function comparison Compare complex data structures using Java function comparison Apr 19, 2024 pm 10:24 PM

When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure Jun 03, 2024 am 09:58 AM

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

In-depth understanding of reference types in Go language In-depth understanding of reference types in Go language Feb 21, 2024 pm 11:36 PM

Reference types are a special data type in the Go language. Their values ??do not directly store the data itself, but the address of the stored data. In the Go language, reference types include slices, maps, channels, and pointers. A deep understanding of reference types is crucial to understanding the memory management and data transfer methods of the Go language. This article will combine specific code examples to introduce the characteristics and usage of reference types in Go language. 1. Slices Slices are one of the most commonly used reference types in the Go language.

Hash table-based data structure optimizes PHP array intersection and union calculations Hash table-based data structure optimizes PHP array intersection and union calculations May 02, 2024 pm 12:06 PM

The hash table can be used to optimize PHP array intersection and union calculations, reducing the time complexity from O(n*m) to O(n+m). The specific steps are as follows: Use a hash table to map the elements of the first array to a Boolean value to quickly find whether the element in the second array exists and improve the efficiency of intersection calculation. Use a hash table to mark the elements of the first array as existing, and then add the elements of the second array one by one, ignoring existing elements to improve the efficiency of union calculations.

Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Feb 23, 2024 am 10:49 AM

Overview of Java Collection Framework The Java collection framework is an important part of the Java programming language. It provides a series of container class libraries that can store and manage data. These container class libraries have different data structures to meet the data storage and processing needs in different scenarios. The advantage of the collection framework is that it provides a unified interface, allowing developers to operate different container class libraries in the same way, thereby reducing the difficulty of development. Data structures of the Java collection framework The Java collection framework contains a variety of data structures, each of which has its own unique characteristics and applicable scenarios. The following are several common Java collection framework data structures: 1. List: List is an ordered collection that allows elements to be repeated. Li

Learn the secrets of Go language data structures in depth Learn the secrets of Go language data structures in depth Mar 29, 2024 pm 12:42 PM

In-depth study of the mysteries of Go language data structure requires specific code examples. As a concise and efficient programming language, Go language also shows its unique charm in processing data structures. Data structure is a basic concept in computer science, which aims to organize and manage data so that it can be accessed and manipulated more efficiently. By in-depth learning the mysteries of Go language data structure, we can better understand how data is stored and operated, thereby improving programming efficiency and code quality. 1. Array Array is one of the simplest data structures

C language data structure: the key role of data structures in artificial intelligence C language data structure: the key role of data structures in artificial intelligence Apr 04, 2025 am 10:45 AM

C Language Data Structure: Overview of the Key Role of Data Structure in Artificial Intelligence In the field of artificial intelligence, data structures are crucial to processing large amounts of data. Data structures provide an effective way to organize and manage data, optimize algorithms and improve program efficiency. Common data structures Commonly used data structures in C language include: arrays: a set of consecutively stored data items with the same type. Structure: A data type that organizes different types of data together and gives them a name. Linked List: A linear data structure in which data items are connected together by pointers. Stack: Data structure that follows the last-in first-out (LIFO) principle. Queue: Data structure that follows the first-in first-out (FIFO) principle. Practical case: Adjacent table in graph theory is artificial intelligence

See all articles