How to create HashMap in JS file (in JQM)

I am developing a mobile app using jQuery Mobile. Wanted to know if I can create a HashMap the way we can do it in JAVA, in JQuery Mobile?

If so, how? please provide me with an example if possible.

+3


source to share


3 answers


In plain Javascript, you can create something very similar to the java HashMap:

var hashmap = {};

      

Put something in it:

hashmap['key'] = 'value';

      



Get something from this:

var value = hashmap['key'];

      

For most purposes this will do, but it is not exactly the same as a hashmap , see for example this question: JavaScript Hashmap Equivalent

+11


source


Javascript (EcmaScript 5) currently only has Objects and Arrays. ES Harmony will be introducing Cards and Sets, but it's a long way to go until it gets wide enough support to be used effectively.

You can use a regular object, it behaves like a Java Hashmap in most cases.



// initialisation
var o = { key:"value", "another key", 3};
// or
var o = {};
o.key = "value";
// access property
alert(o.key);         // dot-notation
alert(o["key"]);      // bracket notation, same as array[i]
// delete property
delete o.key;

      

If the key is a valid identifier, you do not need to quote it, and it is also easy to access it using dot notation, if not (a reserved keyword or spaces in it or ...), you need to quote it with double or single quotes and address it with parentheses.

0


source


An easy way to dynamically create a map in JavaScript is to use the following method.

I am creating a map using an array that contains the id of the html elements. In the end, I want to put the elements and values ​​of the html elements in a key-value pair in the map.

var selectedFilterValuesMap = {};

for (var i = 0; i < filterIdArray.length; i++) {        
    selectedFilterValuesMap[filterIdArray[i].trim()] = $("#"+filterIdArray[i].trim()).val();
}

      

And I can access the values ​​in the map like this:

for(var x in selectedFilterValuesMap){
    alert("key - "+x+"\n val - "+selectedFilterValuesMap[x]);
}

      

0


source







All Articles