Maps - Javascript
We output the key and its associated value.
//1. Creating a Map, and looping though it.
//Create a map, a collection of key value pairs
var myTranslation = {
"my house": "mein Haus",
"my boat": "mein Boot",
"my horse": "mein Pferd"
}
// quick console test..
myTranslation
Object {my house: "mein Haus", my boat: "mein Boot", my horse: "mein Pferd"}
//Loop through all keys logic.
var i=0, key="", keys=[];
keys = Object.keys( myTranslation);
for (i=0; i < keys.length; i++) {
key = keys[i];
alert('The translation of '+ key +' is '+ myTranslation[key]);
}
//2. Adding a value
// SYN : • Mapname | ["Key"] = "value";
myTranslation["my car"] = "mein Auto";
//3. Delete
//Delete a Map Entry : simply cite the key with the delete operator.
delete myTranslation["my boat"];
//4. Search for an element within the array
if ("my horse" in myTranslation) {
console.log("true")
} else {
console.log("false")
}
// true
if ("my pencil" in myTranslation) {
console.log("true")
} else {
console.log("false")
}
// false