这是我的第一个“程序”或任何你想用 JavaScript 调用它的东西。
我需要修改avg
,total
以及grade
通过使用2个功能:calcAVG
和calcGrade
。我无法使该calcAVG
功能正常工作。我无法弄清楚为什么该函数不会修改avg
ortotal
值。在程序中,我无法修改对象的前 5 个属性(用于赋值)。
该calcAVG
函数在console.log
. 那么我是否有某种语法错误?
var student = {
fullName : 'Amanda Corbin',
scores : [90,50,88,56,89],
avg : 0,
total : 0,
grade : '',
calcAvg : function(scores,avg,total) {
for (var i = 0; i < this.scores.length; i++) {
this.total += this.scores[i];
}
this.avg = ( this.total / this.scores.length );
return (this.avg);
}
calcGrade : function(avg,grade) {
if (this.avg >=90){
console.log("grade is A");
this.grade = 'A';
} else if (this.avg >= 80 && this.avg <90){
console.log("grade is B");
this.grade = 'B';
} else if (this.avg >= 70 && this.avg <80){
console.log("grade is C");
this.grade = 'C';
} else if (this.avg >= 60 && this.avg <70){
console.log("grade is D");
this.grade = 'D';
} else if (this.avg <60){
console.log("grade is F");
this.grade = 'F';
}
return (this.grade);
}
console.log(student);
console.log(student.calcAvg());
console.log(student.calcGrade());
克里斯在上面的评论中是正确的。
您的最终代码应如下所示
var student = {
fullName : 'Amanda Corbin',
scores : [90,50,88,56,89],
avg : 0,
total : 0,
grade : '',
calcAvg : function(scores,avg,total) {
for (var i = 0; i < this.scores.length; i++) {
this.total += this.scores[i];
}
this.avg = ( this.total / this.scores.length );
return (this.avg);
},
calcGrade : function(avg,grade) {
if (this.avg >=90){
console.log("grade is A");
this.grade = 'A';
} else if (this.avg >= 80 && this.avg <90){
console.log("grade is B");
this.grade = 'B';
} else if (this.avg >= 70 && this.avg <80){
console.log("grade is C");
this.grade = 'C';
} else if (this.avg >= 60 && this.avg <70){
console.log("grade is D");
this.grade = 'D';
} else if (this.avg <60){
console.log("grade is F");
this.grade = 'F';
}
return (this.grade);
}
}
console.log(student);
console.log(student.calcAvg());
console.log(student.calcGrade());
这是 coderpad 沙箱链接上相同的输出(只需复制粘贴上面的代码,您就可以看到输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句