Javascript 如何使用javascript字典中的键查找值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11393200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find value using key in javascript dictionary
提问by A_user
I have a question about Javascript's dictionary. I have a dictionary in which key-value pairs are added dynamically like this:
我有一个关于 Javascript 字典的问题。我有一个字典,其中键值对是动态添加的,如下所示:
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
由于我的密钥是一个变量,我不能使用 Dict.my_key
Thanks.
谢谢。
回答by Matt Gibson
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
JavaScript 中的数组不使用字符串作为键。您可能会发现值在那里,但键是一个整数。
If you make Dict
into an object, this will work:
如果你做成Dict
一个对象,这将起作用:
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.
该myKey
变量已经是一个字符串,所以你不需要更多的引号。