I am developing a mobile app using JQuery Mobile. Wanted to know whether can i create a HashMap the way we can do it in JAVA, in JQuery Mobile?
If yes, then how? please if possible provide me some example.
I am developing a mobile app using JQuery Mobile. Wanted to know whether can i create a HashMap the way we can do it in JAVA, in JQuery Mobile?
If yes, then how? please if possible provide me some example.
In plain Javascript it is possible to create something very similar to a java HashMap:
var hashmap = {};
Put something in it:
hashmap['key'] = 'value';
Get something out of it:
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
Javascript (EcmaScript 5) currently only has Objects and Arrays. ES Harmony will introduce Maps and Sets, but that's quite a long way until it has wide enough support to effectively use it.
You can use an ordinary Object, in most cases it behaves like a Java-Hashmap.
// 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 don't need to quote it and also can access it easily with dot-notation, if not (reserved keyword or spaces in it or ...), you need to quote it with either double or single quotes and address it with bracket notation.
An easy way to dynamically create a map in JavaScript is to use the following way.
I'm creating a map using an array which contains the id of html elements. In the end, I want to put the html elements ids and values in a key-value pair in a 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]);
}