我有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);
答案 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);