In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use Set and Map to store data". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Set and Map to store data".
Programmers have been using Object and Array to store data for many years, and this trend is not limited to JavaScript. Apart from these two options, there is no other option to store multiple values and work with data structures. However, there are several restrictions when using Object and Array, such as:
Array can store duplicate elements.
There is no way to find the Object length as Array does.
Only strings can be stored in Object without remembering the insertion order.
The developer must select an array or object based on the use case.
Third-party libraries such as Lodash are used to enhance the functionality of arrays.
With the release of ES6 in 2015, things began to improve. ES6 introduces support for Map and Set to overcome the above limitations.
What are Set and Map?
As mentioned earlier, both features were introduced in the ES6 version of JavaScript. Set is an ordered collection of unique elements. "unique element" is the most important because it means that duplicate elements cannot be stored in a Set. But it has no key-value pair system.
Map is a combination of Array and Object data structures. It is the Set of the key-value pair like Object, but it also remembers the insertion format and has the length (.size) attribute.
Declaration and initialization of Set: a collection can be initialized like this.
Const set = new Set ()
Const set = new Set ()
Add and remove elements from Set: you can easily insert elements into the collection using the .add () method.
Const set = new Set (); set.add ('John'); set.add (' Martha') set.add ('Bryan'); set.add (' John'); / / set = {'John','Martha','Bryan'}
Set in JavaScript borrows attributes from many mathematical collections and contains only unique elements. Deleting an element is also very simple, using the .delete () method to delete a single element, or using the .clear () method to delete all elements.
Set.add ('John'); set.add (' Martha') set.add ('Bryan'); set.delete (' Martha') / / set= {'John','Bryan'} set.clear (); / / removes all the element
Size of Set: with .size, you can easily find the size of a useful Set.
Set.add ('a') set.add ('b'); set.add ('c'); console.log (set.size) / / = > 3
Accessing elements in Set: Set tries to record or access its values in a different way. You can record arrays and view elements, but this does not apply to Set.
Var arr= [1mem2jue 3]; const set = new Set (arr); console.log (set) / / = > [objectSet] console.log (arr) / / = > (3) [1meme 2mer3]
To access Set, we need a SetIterator () to get all the values. JavaScript provides a property .values () to get an iterator, which we can then use in conjunction with the loop to get all the values. As demonstrated in the following code snippet:
Var arr= [1Jing 2Jue 3]; const set = new Set (arr); variterator=set.values () console.log (iterator.next (). Value) / / 1
An easier way to retrieve all elements is to use .forEach (), as follows:
Var arr= [1Jing 2Jue 3]; const set = new Set (arr); set.forEach (v = > console.log (v))
Output:
1 2 3
In addition, you can use the .has () method to check whether a value exists, and if the element is found, the method will return true.
Var arr= [1Jing 2Jue 3]; const set = new Set (arr); console.log (set.has (1)); / / true
It is worth mentioning that although Set does not support key-value pairs elements, methods such as keys () and entries () are available for Set.
Set vs Array
Set and Array tend to perform and handle the same operations, but there are some differences. The biggest difference is that Set cannot have duplicates like Array, while Set provides an easier way to delete items. In addition, the elements of Set are iterable in the insertion order.
Like mathematical collections, collections in JavaScript can also be used to perform operations such as union and intersection, which can be used when merging data or finding common elements in two Set.
Initialize and declare Map:
Similar to Set, Map can be declared in the same way.
Const map = new Map ()
Add and remove elements from Map: Map supports Object-like key-value pairs. Therefore, while adding value, we also need to provide a key. This is different from what we see in Set.
Const map = new Map (); map.set ('Name',' iPhone'); / / map.set (key,value) formatmap.set ('Brand',' Apple'); map.set ('Price',' $1000')
To delete a value from Map, we can simply pass the key to the .delete () attribute.
Const map = new Map (); map.set ('Name',' iPhone'); map.set ('Brand','Apple'); map.set (' Price','$1000'); map.delete ('Price'); / / removes the elementwith key' Price'
Similar to Set, you can delete all elements using .clear ().
Map.clear () / / removes all the element
Size of Map: the size (length) of the Map can be easily retrieved using .size.
Const map = new Map (); map.set ('Name',' iPhone'); map.set ('Brand','Apple'); map.set (' Price','$1000'); console.log (map.size) / / = > 3
Access elements in Map: Map provides us with a .get () method that quickly gets the value by passing the key as an argument to the method.
Const map = new Map (); map.set ('Name',' iPhone'); map.set ('Brand','Apple'); map.set (' Price','$1000'); console.log (map.get ('Name')); / / iPhoneconsole.log (map.get (' Brand')); / / Apple
But what if you just want keys, values, or both? Map has .keys (), .keys () and .keys () to do the same thing. Use the same Map in the above code:
Console.log (map.keys ()); / iterator {'Name','Brand',Price'} console.log (map.values ()); / / iterator {' iPhone','Apple','$1000'} console.log (map.entries ()); / / iterator {'Name':'iPhone','Brand':'Apple',Price':'$1000'}
The iteration of Map is also very simple:
/ / with for-each map.forEach ((value, key) = > {console.log (`${key} is ${value} yearsold!`);}); / / with for-of for (const [key, value] of map) {console.log (`${key}: ${value}`);}
In addition, you can easily check the existence of the element using the. Has () attribute and passing the key.
Var map = new Map (); map.set ('age',19); console.log (map.has (' age')) / / true since 'age' key ispresent
If you decide to convert object to map,JavaScript, it's done. We used .arguments () to get all the key-value pairs, but this time we will use the method for Object.
Const myObject= {'Age':' 25, 'Gender':' Male', 'Nationality':' Australian'}; const myMap = new Map (Object.entries (myObject)); / / object to mapconstanotherObject = Object.fromEntries (myMap) / / map to object
You can easily convert map to object, as shown above. To convert Map to Array, you can use array. From (myMap).
Map vs Array & Objects
Map seems to address many of the shortcomings of Array and Object, such as its ability to handle more complex operations. Map is like a mixture of Array and Object. It has an array-like size attribute that stores elements in key-value pairs. In addition, it provides methods such as. Has () to check whether the element exists, which can save a lot of time.
Moreover, it does not require that the key must be of a string type. You can even use an object as a key to help you write better code.
Although Array and Object have become de facto standards for storing collections and key-value pairs of elements, by introducing Map and Set, you can provide an interesting way for your code. Set and Map are new standards provided by JavaScript for storing complex data structures.
In addition, the use of these data structures eliminates the need for third-party libraries, such as Lodash, because these new data structures provide methods such as .has () and .delete () by default.
Thank you for reading, the above is the content of "how to use Set and Map to store data". After the study of this article, I believe you have a deeper understanding of how to use Set and Map to store data, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.