Home > Article > Web Front-end > 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
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:
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.
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.
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)]
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 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?
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.
The methods that can use WeakMap are as follows.
The biggest difference in this topic is that WeakMap does not support iteration Object methods. But why? This is described below.
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 is also very similar to Map, but Set is more useful for a single value.
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-of
或 forEach
语句。
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);
与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-of
或 forEach
,因为它不可迭代。
相同点:添加相同的值不支持。
Map vs. WeakMap:WeakMap仅接受对象作为键,而Map不接受。
Map and Set:
for..of
,forEach
或 ...
运算符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!