Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  102] [ 7]  / answers: 1 / hits: 178483  / 12 Years ago, mon, july 9, 2012, 12:00:00

I have a question about Javascript's dictionary. I have a dictionary in which key-value pairs are added dynamically like this:



var Dict = []
var addpair = function (mykey , myvalue) [
Dict.push({
key: mykey,
value: myvalue
});
}


I will call this function and pass it different keys and values. But now I want to retrieve my value based on the key but I am unable to do so. Can anyone tell me the correct way?



var givevalue = function (my_key) {
return Dict[' +my_key +'] // not working
return Dict[' +my_key +'].value // not working
}


As my key is a variable, I can't use Dict.my_key



Thanks.


More From » dictionary

 Answers
4

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.



If you make Dict into an object, this will work:



var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};


The myKey variable is already a string, so you don't need more quotes.


[#84383] Saturday, July 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
charity

Total Points: 503
Total Questions: 98
Total Answers: 125

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
;