Map:
- Map store elements using keys. (Key=Value pairs)
- Map working like dictionary.
- Keys must be unique (not duplicated)
- Values can be duplicated
For example, we process accounts using account numbers because names can be duplicated but account numbers must be unique.
var accounts = [ [101 : ‘amar’], [102 : ‘annie’], [103 : ‘amar’] ];
Map object providing pre-defined methods to process:
Clear() | removes all elements from map object |
Delete(key) | removes element associated with specified key. |
Get(key) | returns the element associated with the key |
Has(key) | returns true if value associated with the key, else returns false |
Keys() | returns set of keys in this map object |
Values() | returns set of Values in this map object |
Set(key, value) | set the value of existing key in the Map |
Create Map and display element with key:
<!doctype html>
<html>
<body>
<script>
var accounts = new Map([
[101, 'Amar'],
[102, 'Annie'],
[103, 'Sathya']]);
document.write(accounts.get(102));
</script>
</body>
</html>
Display all keys from the Map:
<!doctype html>
<html>
<body>
<script>
var accounts = new Map([
[101, 'Amar'],
[102, 'Annie'],
[103, 'Sathya'],
[104, 'Harsha']]);
var arr = accounts.keys();
document.write("keys : <br/>");
for(var k of arr)
{
document.write(k + "<br/>");
}
</script>
</body>
</html>
Display all elements of Map:
<!doctype html>
<html>
<body>
<script>
var accounts = new Map([
[101, 'Amar'],
[102, 'Annie'],
[103, 'Sathya'],
[104, 'Harsha']]);
var arr = accounts.keys();
document.write("keys & Values : <br/>");
for(var k of arr)
{
var v = accounts.get(k);
document.write(k + " : " + v + "<br/>");
}
</script>
</body>
</html>