5+ Js Map 使い方 References
Introduction
JavaScript (JS) is a popular programming language that is used to add interactive elements to web pages. One of the most useful JS features is the Map object, which allows developers to easily store and retrieve key-value pairs. In this article, we will explore the basics of using JS Map and its various methods to make your web development tasks easier.
Creating a Map
Before we can use JS Map, we need to create one. To create a new Map, we simply use the new keyword followed by the Map constructor. Here's an example:
let myMap = new Map();This creates an empty Map that we can now add key-value pairs to.
Adding Key-Value Pairs
To add a key-value pair to a Map, we use the set() method. Here's an example:
myMap.set('name', 'John');This adds a new key-value pair to myMap where the key is 'name' and the value is 'John'.
Retrieving Values
To retrieve a value from a Map, we use the get() method. Here's an example:
let name = myMap.get('name');This retrieves the value associated with the key 'name' and assigns it to the variable name.
Checking if a Key Exists
To check if a key exists in a Map, we use the has() method. Here's an example:
if (myMap.has('name')) { console.log('Name exists!'); }This checks if the key 'name' exists in myMap and logs a message to the console if it does.
Getting the Number of Key-Value Pairs
To get the number of key-value pairs in a Map, we use the size property. Here's an example:
let numPairs = myMap.size;This assigns the number of key-value pairs in myMap to the variable numPairs.
Iterating Over a Map
To iterate over a Map, we can use a for...of loop. Here's an example:
for (let [key, value] of myMap) { console.log(key + ': ' + value); }This logs each key-value pair in myMap to the console.
Deleting a Key-Value Pair
To delete a key-value pair from a Map, we use the delete() method. Here's an example:
myMap.delete('name');This deletes the key-value pair with the key 'name' from myMap.
Clearing a Map
To remove all key-value pairs from a Map, we use the clear() method. Here's an example:
myMap.clear();This removes all key-value pairs from myMap.
Conclusion
In this article, we have learned the basics of using JS Map and its various methods. By using JS Map, you can easily store and retrieve key-value pairs in your web development projects, making your code more efficient and organized.
0 Response to "5+ Js Map 使い方 References"
Posting Komentar