I'm new in JavaScript. My need is to use key-value data in it. But I didn't see the dictionary data type in JavaScript. Can somebody help me what is the best data type I should use for this purpose.
Thanks & Regards, Abhishek
I'm new in JavaScript. My need is to use key-value data in it. But I didn't see the dictionary data type in JavaScript. Can somebody help me what is the best data type I should use for this purpose.
Thanks & Regards, Abhishek
just use an object:
var obj = {};
obj["a"]=5;
console.log(obj["a"]); // 5
In Javascript you can imagine every object as a key-value object.
For your purpose just use the following code:
var myDict = {};
myDict.object1 = 42;
You can also use numbers and strings as keys:
var key = "message";
myDict[key] = "hello";
alert(myDict[key]);
var key2 = 5;
myDict[key2] = "five";
I hope that i could help you.
The latest Javascript standard (known as "EcmaScript6") adds a new type called Map (see Mozilla Developer Network - JS API reference) which has less disadvantages than using a simple object.
Here is some code (taken from the website):
var myMap = new Map();
myMap.set("myKey", "value associated with 'a string'");
myMap.size; // 1
myMap.get("myKey"); // "value associated with 'a string'"
Note that is only supported in newer browsers (see Browser compatibility table here).
Thanks all for the quick reply:
I've solve it in this way:
var myCompDetail = {brand:"Dell", model:"Vostro", price:"15k"};
Thanks & Regards,
Abhishek Kumar
You can use the Object data-type for this purpose in JavaScript.
Step-1: Declare the variable
var car = {type:"Fiat", model:"500", color:"white"};
Step-2: Use it wherever required, like below:
car.type, or car.model, or car.color
Hope it will help you.
For more info you can go here: http://www.w3schools.com/js/js_objects.asp
Thanks & Regards,
Arun Dhwaj