JS新手在这里,并有传递参数的问题。我在一个对象内部编写一个函数,并且无法弄清楚为什么JS不能在函数中传递我的参数。见下面的例子
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": {
testScores: scores[0]
},
"Susan": {
testScores: scores[1]
},
"William": {
testScores: scores[2]
},
"Elizabeth": {
testScores: scores[3]
},
addScore: function(student, score){
console.log(student) //=> output as expected
console.log(score) //=> output as expected
console.log(gradebook.Joseph.testScores) //=> this works as expected and shows Joseph's scores
console.log(gradebook.student.testScores) //=> gives TypeError: Cannot read property 'testScores' of undefined
}
};
gradebook.addScore("Joseph", 30);
我将控制台日志语句调试并弄清楚最新情况。当我在学生姓名中进行硬编码时,我不知道为什么这会起作用,但是当我将学生的名字作为参数传递给成绩簿对象之外的函数时,它不起作用。任何帮助将不胜感激!
答案 0 :(得分:1)
使用[]代替点。 成绩簿[学生] .testScores应该给你想要的结果。