在JavaScript中获取对象的属性 [英] Get property of object in JavaScript

查看:95
本文介绍了在JavaScript中获取对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个带有< select> 的表单,它选择使用哪组数据(值为m,f和c) 。然后我有一个包含以下数据的字典/对象:

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:

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.
};

现在我需要 gdas.m / gdas.f / gdas.c 但我不确定使用什么语法 - 我试过了:

Now I need to get gdas.m/gdas.f/gdas.c but I'm not sure what syntax to use - I've tried:

var mode = $("#mode").val();
var gda_set = gdas.mode;
var gda_set = gdas[mode];

这是什么样的语法/方法?

What's the right syntax/method for this?

推荐答案

由于您通过变量引用该属性,因此需要括号表示法。

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"];

这篇关于在JavaScript中获取对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆