Javascript 如何使用变量引用对象字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3547663/
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 refer to object fields with a variable?
提问by liysd
Let's asume that I have an object:
假设我有一个对象:
var obj = {"A":"a", "B":"b", "x":"y", "a":"b"}
When I want to refer to "A" I just write obj.A
当我想提到“A”时,我只写 obj.A
How to do it when I have key in a variable, i.e.:
当我有一个变量的键时怎么做,即:
var key = "A";
Is there any functionthat returns a value or null(if key isn't in the object)?
是否有任何函数返回值或null(如果键不在对象中)?
回答by Nick Craver
Use bracket notation, like this:
使用括号表示法,如下所示:
var key = "A";
var value = json[key];
In JavaScript these two are equivalent:
在 JavaScript 中,这两个是等价的:
object.Property
object["Property"];
And just to be clear, this isn't JSON specific, JSON is just a specific subset of object notation...this works on any JavaScript object. The result will be undefinedif it's not in the object, you can try all of this here.
需要明确的是,这不是特定于 JSON 的,JSON 只是对象符号的一个特定子集……这适用于任何 JavaScript 对象。结果将是undefined如果它不在对象中,您可以在此处尝试所有这些。
回答by Bobby Hyman
How about:
怎么样:
json[key]
Try:
尝试:
json.hasOwnProperty(key)
for the second part of your question (see Checking if a key exists in a JavaScript object?)
对于问题的第二部分(请参阅检查 JavaScript 对象中是否存在键?)

