In JavaScriptMap
Objects save key-value pairs and are able to remember the original insertion order of keys
Here is how to use it in JavaScriptMap
Summary of the blog post of the object:
1. Create and initialize Map objects
usenew Map()
The constructor can create a new oneMap
Object. You can also pass an iterable object (such as a key-value pair array) into the constructor to initializeMap
Object.
const map1 = new Map(); // Create an empty Map objectconst map2 = new Map([ ['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3'] ]); // Initialize arrays using key-valueMapObject
2. Add and get key-value pairs
useset()
Method toMap
Add key-value pairs to the object, useget()
The method obtains the corresponding value according to the key.
('key1', 'value1'); ('key2', 'value2'); (('key1')); // Output: 'value1'(('key2')); // Output:'value2'
3. Check whether the key exists
usehas()
Method CheckMap
Whether the specified key exists in the object.
(('key1')); // Output: true(('key3')); // Output:false
4. Delete key-value pairs
usedelete()
Method fromMap
Deletes the specified key and its corresponding value in the object.
('key1'); (('key1')); // Output:false
5. Iterate over Map objects
Map
Objects supportforEach()
Method orfor...of
Loop to traverse.
// Use the forEach() method to traverse((value, key) => { (`${key}: ${value}`); }); // Loop through with for...offor (const [key, value] of map1) { (`${key}: ${value}`); }
6. Comparison between Map objects and other data structures
Map
Object andObject
andWeakMap
Other data structures, etc., have some differences when storing key-value pairs. For example,Map
The object can remember the insertion order of the keys, andObject
The order of attributes may vary across JavaScript engines. in addition,WeakMap
Only accept objects as keys, which makes it more important in certain scenariosMap
Objects are more suitable.
7. Summary
Map
Objects provide a flexible and efficient way to store key-value pairs in JavaScript. It has many practical methods, such asset()
、get()
、has()
anddelete()
etc., making it easier to operate and manage key-value pairs. also,Map
Objects can also remember the insertion order of keys, which is very useful in some application scenarios.
This is all about this article about map attributes in JS. For more related map attribute content in js, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!