Javascript 如何根据键从对象文字中返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4113083/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:39:04  来源:igfitidea点击:

How to return a value from an Object Literal based on a key?

javascriptjquery

提问by user357034

I have an array as follows. How would I retrieve the value of a specific key and put that value in a variable?

我有一个数组如下。我如何检索特定键的值并将该值放入变量中?

var obj = {"one":"1","two":"3","three":"5","four":"1","five":"6"};

So for instance if I want to get the value of "three" how would I do it in javascript or jQuery?

因此,例如,如果我想获得“三”的值,我将如何在 javascript 或 jQuery 中做到这一点?

回答by Nick Craver

You can do this via dotor bracketnotation, like this:

您可以通过括号表示法来执行此操作,如下所示:

var myVariable = obj.three;
//or:
var myVariable = obj["three"];

In the second example "three"could be a string in another variable, which is probablywhat you're after. Also, for clarity what you have is just an object, not an array :)

在第二个示例中"three"可能是另一个变量中的字符串,这可能是您所追求的。另外,为了清楚起见,您所拥有的只是一个对象,而不是数组:)

回答by Boshika Tara

Here is a solution (by the way this is an object not an array):

这是一个解决方案(顺便说一下,这是一个对象而不是数组):

var obj = {"one":"1","two":"3","three":"5","four":"1","five":"6"};
var myFunc = function(thisObj, property) {console.log(obj[property])};
myFunc(obj, "two");
//Output will be 3

You can also do this more easily using the _.pluckfunction from the Underscore JS library.

您还可以使用_.pluckUnderscore JS 库中的函数更轻松地执行此操作。