JavaScript Map Methods
Maps have various methods to efficiently manage key-value pairs. Understanding these methods allows for flexible and powerful data handling.
Key Topics
- set(), get(), has(), delete()
- clear(), size
- keys(), values(), entries()
- forEach() Method
- JavaScript Usage in DOM
- Key Takeaways
set(), get(), has(), delete()
set()
adds or updates entries, get()
retrieves values, has()
checks for existence, and delete()
removes entries.
clear(), size
clear()
removes all entries, and size
gives the count of key-value pairs.
keys(), values(), entries()
These return iterators for keys, values, and [key, value] pairs, enabling easy iteration.
forEach() Method
forEach()
executes a callback for each key-value pair, allowing custom processing of map entries.
let m = new Map([ ["k1", "v1"], ["k2", "v2"] ]);
m.forEach((value, key) => {
console.log(key + ": " + value);
});
Output
> k1: v1
> k2: v2
Explanation: forEach()
iterates over each entry, printing key and value.
JavaScript Usage in DOM
Use map methods to dynamically update or retrieve settings, translations, or other key-value data and show them on the webpage.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Map Methods in DOM</title></head>
<body>
<h1>Map Methods Demo</h1>
<button onclick="showMapData()">Show Data</button>
<p id="display"></p>
<script>
function showMapData() {
let dataMap = new Map();
dataMap.set("Lang", "JavaScript");
dataMap.set("Version", "ES6");
let result = "";
dataMap.forEach((value, key) => {
result += key + ": " + value + " ";
});
document.getElementById("display").textContent = result;
}
</script>
</body>
</html>
Key Takeaways
- Core Methods:
set()
,get()
,has()
,delete()
- Structure:
clear()
,size
manage the map's overall data - Iteration:
keys()
,values()
,entries()
, andforEach()
allow flexible data processing - DOM Integration: Easily retrieve and display map-based data.