对象内部的函数无法正常工作 - Javascript

阿曼达·科尔宾

这是我的第一个“程序”或任何你想用 JavaScript 调用它的东西。

我需要修改avgtotal以及grade通过使用2个功能:calcAVGcalcGrade我无法使该calcAVG功能正常工作。我无法弄清楚为什么该函数不会修改avgortotal值。在程序中,我无法修改对象的前 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());

grane2212

克里斯在上面的评论中是正确的。

您的最终代码应如下所示

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章