在 JavaScript 中获取对象的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3695243/
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
Get property of object in JavaScript
提问by Ross
Basically I have a form with a <select>that chooses which set of data to use (values are "m", "f" and "c"). I then have a dictionary/object with the data in:
基本上,我有一个带有 a 的表单,<select>用于选择要使用的数据集(值为“m”、“f”和“c”)。然后我有一个包含数据的字典/对象:
var gdas = {
// Male
"m": {
"calories": 2500,
"protein": 55,
"carbohydrates": 300,
"sugars": 120,
"fat": 95,
"saturates": 30,
"fibre": 24,
"salt": 6
},
// Female
"f": {
"calories": 2000,
// etc.
};
Now I need to get gdas.m/gdas.f/gdas.cbut I'm not sure what syntax to use - I've tried:
现在我需要gdas.m/ gdas.f/gdas.c但我不知道如何使用语法-我已经试过:
var mode = $("#mode").val();
var gda_set = gdas.mode;
var gda_set = gdas[mode];
What's the right syntax/method for this?
什么是正确的语法/方法?
回答by user113716
Since you're referencing the property via a variable, you need the bracket notation.
由于您通过变量引用属性,因此需要括号表示法。
var gda_set = gdas[mode];
...which is the same notation you would use if you were passing a String.
...这与传递字符串时使用的符号相同。
var gda_set = gdas["f"];
回答by Tomasz Kowalczyk
You don't have "mode" attribute in that variable. You must use if's to detect which sex you are processing and get gdas.m.fibreor gdas.f.salt.
您在该变量中没有“模式”属性。您必须使用 if's 来检测您正在处理的性别并获得gdas.m.fibreor gdas.f.salt。
回答by halfdan
You can use gdas[mode], it selects the element that is indexed by the value of mode.
您可以使用 gdas[mode],它选择由 mode 值索引的元素。

