变量对象属性名称作为javascript中的参数?

时间:2015-11-20 04:57:46

标签: javascript

我有javascript对象如下:

var school = {
    grade1:[
    {
    "teacher":"anna",
    "student":"jacky"
    },
    {..},...
    ]
    grade2:[...]   
}

我尝试使用函数

检索内容时遇到了问题
function getNames(grade){
    $('#demo').text(school.grade[0].teacher); //returns an error
}

我可以使用school.grade1[0].teacher,但我想要一个grade变量。

当我尝试这个时,它显然不起作用:

var grade = 'grade1'; //I also tried just grade1 but it is an undefined varaible
getNames(grade); 

2 个答案:

答案 0 :(得分:1)

你可以做到

school[grade][0].teacher

答案 1 :(得分:0)

您可以尝试这样:

function getNames(grade){
    $('#demo').text(grade.teacher);
}

var grade = school.grade1[0]
or
var grade = school.grade2[0]
getNames(grade);