Table of Contents
Objects
Map
How to add attributes
How to iterate over an object
How to delete attributes
WeakMap
Difference 1: key must be an object
Difference 2: Not all methods in Map are supported
Difference 3: When GC cleans up references, the data will be deleted
Set
如何遍历对象
如何删除属性
WeakSet
比较总结
结语
Home Web Front-end JS Tutorial A brief discussion on Map, WeakMap, Set and WeakSet in JavaScript

A brief discussion on Map, WeakMap, Set and WeakSet in JavaScript

Jan 30, 2021 pm 06:19 PM
javascript map set

A brief discussion on Map, WeakMap, Set and WeakSet in JavaScript

I would guess that over 70% of JavaScript developers only use objects to collect and maintain data in their projects. Well, it's true, new collection objects like Map and Set are underutilized even when they came out in 2015.

So, today, I will discuss the amazing new features from 2015 - Map, Set, WeakMap and WeakSet .

Before you read

  • This article is not meant to tell you to only use them. But I've seen some candidates use one of these on coding exams, and I like using them in certain situations. It's up to you to decide when to use them in your project.
  • You should know what an iterable is to better understand my discussion.

Objects

We should first discuss how to use objects.

Okay, I believe more than 90% of people already know this part, because you clicked on this article to learn about the new collection object, but for beginners in JavaScript, let’s keep it simple Say them.

const algorithm = { site: "leetcode" };
console.log(algorithm.site); // leetcode

for (const key in algorithm) {
  console.log(key, algorithm[key]);
}

// site leetcode
delete algorithm.site;
console.log(algorithm.site); // undefined
Copy after login

So I made an algorithm object, its key and value are a string type value, and I called it by using the . keyword value.

In addition, for-in loops are also very suitable for looping in objects. You can access the value corresponding to its key using the [] keyword. But for-of loops cannot be used because objects are not iterable.

The properties of an object can be deleted using the delete keyword. In this way, you can completely get rid of the properties of the object. You should be careful not to confuse it with this method.

const algorithm = { site: "leetcode" };
// Property is not removed!!
algorithm.site = undefined;
// Property is removed!!
delete algorithm.site;
Copy after login

algorithm.site = undefined just assigns the new value to site.

Okay, we've quickly discussed a few things about objects:

  • How to add properties
  • How to iterate over objects
  • How to remove properties

Map

Map is a new collection object in JavaScript that functions like an object. However, there are some major differences compared to regular objects.

First, let's look at a simple example of creating a Map object.

How to add attributes

const map = new Map();
// Map(0) {}
Copy after login

Map There is no need to create anything, but the way to add data is slightly different.

map.set('name', 'john');
// Map(1) {"name" => "john"}
Copy after login

Map has a special way to add properties in it called set. It takes two parameters: the key is the first parameter and the value is the second parameter.

map.set('phone', 'iPhone');
// Map(2) {"name" => "john", "phone" => "iPhone"}
map.set('phone', 'iPhone');
// Map(2) {"name" => "john", "phone" => "iPhone"}
Copy after login

However, it does not allow you to add existing data in it. If a value corresponding to the new data's key already exists in the Map object, the new data will not be added.

map.set('phone', 'Galaxy');
// Map(2) {"name" => "john", "phone" => "Galaxy"}
Copy after login

But you can overwrite existing data with other values.

How to iterate over an object

Map is an iterable object, which means it can be mapped using a for-of statement.

for (const item of map) {
  console.dir(item);
}
// Array(2) ["name", "john"]
// Array(2) ["phone", "Galaxy"]
Copy after login

One thing to remember is that Map provides data in the form of an array, you should destructure the array or access each index to get the key or value.

To get only the keys or values, there are some methods available to you.

map.keys();
// MapIterator {"name", "phone"}
map.values();
// MapIterator {"john", "Galaxy"}
map.entries();
// MapIterator {"name" => "john", "phone" => "Galaxy"}
Copy after login

You can even use the spread operator (...) to get the entire data of the Map, because the spread operator also works behind the scenes with iterable objects.

const simpleSpreadedMap = [...map];
// [Array(2), Array(2)]
Copy after login

How to delete attributes

Deleting data from a Map object is also easy, all you need to do is call delete.

map.delete('phone');
// true
map.delete('fake');
// false
Copy after login

delete Returns a Boolean value indicating whether the delete function successfully deleted the data. If so, returns true, otherwise returns false.

WeakMap

WeakMap originated from Map, so they are very similar to each other. However, WeakMap is very different.

Where did the name WeakMap come from? Well, it's because its connection or relationship with the data object pointed to by its reference link is not as strong as that of Map, so it is weak.

So, what does this mean?

Difference 1: key must be an object

const John = { name: 'John' };
const weakMap = new WeakMap();
weakMap.set(John, 'student');
// WeakMap {{...} => "student"}
weakMap.set('john', 'student');
// Uncaught TypeError: Invalid value used as weak map key
Copy after login

You can pass any value into the Map object as a key, but WeakMap is different, it only accepts an object as a key, otherwise, it will return a mistake.

Difference 2: Not all methods in Map are supported

The methods that can use WeakMap are as follows.

  • delete
  • get
  • has
  • set

The biggest difference in this topic is that WeakMap does not support iteration Object methods. But why? This is described below.

Difference 3: When GC cleans up references, the data will be deleted

Compared with Map, this is the biggest difference.

let John = { major: "math" };

const map = new Map();
const weakMap = new WeakMap();

map.set(John, 'John');
weakMap.set(John, 'John');

John = null;
/* John 被垃圾收集 */
Copy after login

When the John object is garbage collected, the Map object will maintain the reference link, while the WeakMap object will lose the link. So when you use WeakMap, you should consider this feature.

Set

Set is also very similar to Map, but Set is more useful for a single value.

How to add attributes

const set = new Set();

set.add(1);
set.add('john');
set.add(BigInt(10));
// Set(4) {1, "john", 10n}
Copy after login

Like Map, Set also prevents us from adding the same value.

set.add(5);
// Set(1) {5}

set.add(5);
// Set(1) {5}
Copy after login

如何遍历对象

由于Set是一个可迭代的对象,因此可以使用 for-offorEach 语句。

for (const val of set) {
  console.dir(val);
}
// 1
// 'John'
// 10n
// 5

set.forEach(val => console.dir(val));
// 1
// 'John'
// 10n
// 5
Copy after login

如何删除属性

这一部分和 Map 的删除完全一样。如果数据被成功删除,它返回 true,否则返回 false

set.delete(5); 
// true

set.delete(function(){});
// false;
Copy after login

如果你不想将相同的值添加到数组表单中,则Set可能会非常有用。

/* With Set */
const set = new Set();
set.add(1);
set.add(2);
set.add(2);
set.add(3);
set.add(3);
// Set {1, 2, 3}

// Converting to Array
const arr = [ ...set ];
// [1, 2, 3]

Object.prototype.toString.call(arr);
// [object Array]

/* Without Set */
const hasSameVal = val => ar.some(v === val);
const ar = [];

if (!hasSameVal(1)) ar.push(1);
if (!hasSameVal(2)) ar.push(2);
if (!hasSameVal(3)) ar.push(3);
Copy after login

WeakSet

与WeakMap一样,WeakSet也将丢失对内部数据的访问链接(如果内部数据已被垃圾收集)。

let John = { major: "math" };

const set = new Set();
const weakSet = new WeakSet();

set.add(John);
// Set {{...}}
weakSet.add(John);
// WeakSet {{...}}

John = null;
/* John 被垃圾收集 */
Copy after login

一旦对象 John 被垃圾回收,WeakSet就无法访问其引用 John 的数据。而且WeakSet不支持 for-offorEach,因为它不可迭代。

比较总结

相同点:添加相同的值不支持。

Map vs. WeakMap:WeakMap仅接受对象作为键,而Map不接受。

Map and Set:

  • 可迭代的对象,支持 for..offorEach... 运算符
  • 脱离GC关系

WeakMap and WeakSet:

  • 不是一个可迭代的对象,不能循环。
  • 如果引用数据被垃圾收集,则无法访问数据。
  • 支持较少的方法。

结语

不过,我想,很多团队或公司还是没有使用Maps或Sets。也许是因为他们觉得没有必要,或者是因为数组仍然可以做到几乎所有他们想要的东西。

然而,在JavaScript中,Maps或Sets可能是非常独特和强大的东西,这取决于每个情况。所以我希望有一天,你能有机会使用它们。

原文地址:https://medium.com/better-programming/map-weakmap-set-weakset-in-javascript-77ecb5161e3

作者:Moon

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of A brief discussion on Map, WeakMap, Set and WeakSet in JavaScript. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Optimize the performance of Go language map Optimize the performance of Go language map Mar 23, 2024 pm 12:06 PM

Optimizing the performance of Go language map In Go language, map is a very commonly used data structure, used to store a collection of key-value pairs. However, map performance may suffer when processing large amounts of data. In order to improve the performance of map, we can take some optimization measures to reduce the time complexity of map operations, thereby improving the execution efficiency of the program. 1. Pre-allocate map capacity. When creating a map, we can reduce the number of map expansions and improve program performance by pre-allocating capacity. Generally, we

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles