How to create map/array in javascript? - Java @ Desk

Friday, July 26, 2013

How to create map/array in javascript?

var keyOne = "keyOne";
var keyTwo = "keyTwo";
var valueOne = "valueOne";
var valueTwo = "valueTwo";
// Map with two keys and two values
var map = {keyOne:valueOne,keyTwo:valueTwo}

// Get function to get the value from key
function get(k){
  return map[k];

// Create an array as shown below
var array = new Array(10);//It creates an empty array of length 10
array[0] = "Array Index 0";
array[1] = "Array Index 1";
array[2] = "Array Index 2";

// Test Results
//alert("Value for key one in a map : "+get("keyOne"));
//alert("Value for key two in a map : "+get("keyTwo"));
//alert("Value from array : " + array[0]);

var arrayWithElements = new Array(10,20,30); //It creates an with 3 elements
var arrayLiteral = [10,20,30]; //It creates an with 3 elements using the array literal

In order to get the key and value from the map if you does not knows the key, then use following code. It may happen if there is a requirement to iterate through the map without having knowlege of keys that are stored in a map. In that case use the below code.
for (var key in map) {
 //alert("Property \"" + key + "\" = " + map[key]);

No comments:

Post a Comment