Home  >  Article  >  Web Front-end  >  A brief discussion on Map, WeakMap, Set and WeakSet in JavaScript

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

青灯夜游
青灯夜游forward
2021-01-30 18:19:332329browse

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

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;

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) {}

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"}

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"}

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"}

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"]

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"}

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)]

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

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

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 被垃圾收集 */

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}

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

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

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

如何遍历对象

由于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

如何删除属性

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

set.delete(5); 
// true

set.delete(function(){});
// false;

如果你不想将相同的值添加到数组表单中,则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);

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 被垃圾收集 */

一旦对象 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:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete