这里是 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);
我将控制台日志语句进行调试并找出发生了什么。我不知道为什么当我在学生姓名中进行硬编码时这会起作用,但当我通过在成绩簿对象外部运行函数时将学生姓名作为参数传递时则不起作用。任何帮助将不胜感激!
最佳答案
使用[]代替点。 成绩簿[student].testScores 应该给你想要的结果。
关于JavaScript 不使用 x.y,其中 y 是变量的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25707627/