我希望在gradebook对象中添加addScore以追加传入分数数组的分数。 但它给了我一个错误。
TypeError:无法读取未定义的属性'testScore'
var students = ["Joseph", "Susan", "William", "Elizabeth"];
var scores = [ [80, 70, 70, 100],
[85, 80, 90, 90],
[75, 70, 80, 75],
[100, 90, 95, 85] ];
var gradebook = {
joseph:{testScore:scores[0]},
susan:{testScore:scores[1]},
william:{testScore:scores[2]},
elizabeth:{testScore:scores[3]},
addGrade:function(stu_name,grade) {
gradebook.stu_name.testScore.push(grade);
}
};
//test call
gradebook.addGrade("susan",100);
console.log(gradebook.susan.testScore); //should display [85 80 90 90 100]
答案 0 :(得分:0)
您不能对动态属性名称使用“点”表示法。但您可以使用括号表示法:
gradebook["joseph"]
// is equivalent to
gradebook.joseph
...但括号中的表达式可以是一个变量,其值为具有您的属性名称的字符串:
var p = "joseph";
gradebook[p]
因此,对于addGrade()
函数,请尝试以下操作:
addGrade:function(stu_name,grade) {
gradebook[stu_name].testScore.push(grade);
}
答案 1 :(得分:0)
使用此:
var gradebook = {
joseph:{testScore:scores[0]},
susan:{testScore:scores[1]},
william:{testScore:scores[2]},
elizabeth:{testScore:scores[3]},
addGrade:function(stu_name,grade) {
gradebook[stu_name].testScore.push(grade);
}
};
答案 2 :(得分:0)