JavaScript嵌套对象变量

时间:2015-11-27 15:51:11

标签: javascript arrays object

我需要使用传入函数的变量动态访问数据模型中的对象变量。

以下是我的代码示例:

数据模型

var Sectors = {
    Automotive: {
        Question1: {
            Strongly_Agree: 43,
            Agree: 35,
            Neither_Agree_Nor_Disagree: 10,
            Disagree: 8,
            Strongly_Disagree: 4,
            Dont_Know: 10
        },
        Question2: {
            Strongly_Agree: 54,
            Agree: 33,
            Neither_Agree_Nor_Disagree: 12,
            Disagree: 5,
            Strongly_Disagree: 4,
            Dont_Know: 2
        }
    },
    Technology: {
        Question1: {
            Strongly_Agree: 43,
            Agree: 35,
            Neither_Agree_Nor_Disagree: 10,
            Disagree: 8,
            Strongly_Disagree: 4,
            Dont_Know: 10
        },
        Question2: {
            Strongly_Agree: 54,
            Agree: 33,
            Neither_Agree_Nor_Disagree: 12,
            Disagree: 5,
            Strongly_Disagree: 4,
            Dont_Know: 2
        }
    }
};

然后我有一个html选择供人们使用,以便他们可以选择他们所在的扇区。然后我需要从我的数据模型中提取数据,具体取决于他们选择比较的扇区。

提取数据的功能

function getData(sector){
    return Sectors.Sectors[sector].Question1.Strongly_Agree;
}

如果我然后进入该行业" Automotive"它没有用。

任何帮助都会很棒。

萨姆

1 个答案:

答案 0 :(得分:2)

你的功能应该是这样的:

function getData(sector){
    return Sectors[sector].Question1.Strongly_Agree;
}