stuart-d2
3/18/2016 - 6:57 PM

Maps - Javascript 1. Setting up a map of keys(english) and their associated values (translation ) 2. Test of myTranslation returns a Object,

Maps - Javascript

  1. Setting up a map of keys(english) and their associated values (translation )
  2. Test of myTranslation returns a Object, with associated k|v pairs
  3. Looping through . We setup our variables, the sentry var, the key a blank string, and keys an array.
  4. We assign the keys array var the Object.Keys funciton and pass in the map to the function.
  5. We setup our for logic to loop through the keys while I is greater than the length of the array.
  6. We assign the key string var the value of the currenty array index ; keys[i].

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