简体   繁体   中英

JavaScript: Getting undefined value

I have written a function that takes an array of objects( students3 ) and prints the name of the student and their average test score.

 var students3 = [ { name : "Anthony", id : 0, grades : [{ id : 0, score : 84},{ id : 1, score : 20},{ id : 2, score : 80}] }, { name : "Winnie", id : 1, grades : [{ id : 0, score : 62},{ id : 1, score : 56},{ id : 2, score : 100}] }, { name : "Pawandeep", id : 2, grades : [{ id : 0, score : 79},{ id : 1, score : 92},{ id : 2, score : 49}] } ]; 

My solution:

 function getAverageScore(student) { var sum = 0; var grades = student.grades; for(var i = 0; i < grades.length; i++) { var grade = grades[i]; sum += grade.score; } var avg = sum/grades.length; return avg; } function printAverageGrade(students) { for(var i = 0; i < students.length; i++) { var student = students[i]; var averageScore = getAverageScore(student); console.log(student.name, averageScore); } } 

Expected result after running console.log(printAverageGrade(students3)); is:

Anthony 61.333333333333336

Winnie 72.66666666666666

Pawandeep 73.33333333333333

My result:

Anthony 61.333333333333336

Winnie 72.66666666666666

Pawandeep 73.33333333333333

undefined

Anyone can tell me why I am getting an undefined value in my result? Thank you.

The printAverageGrade function itself itself logs messages to the console. It doesn't have a return statement, so it returns undefined .

If you log printAverageGrade(students3) to the console, you will log undefined .

Solution: don't log printAverageGrade(students3) :

console.log(printAverageGrade(students3))printAverageGrade(students3)

That last line is the return value of the function. If you look at the getAverageScore(student) function, you can see that you return avg; , which is what gives that value.

printAverageGrades doesn't return anything, so its return value is undefined . The console logging works though, so as long as you don't try to use it to set any variables, this code is fine.

If you are running from your browser's JavaScript console, are you sure you're not seeing the return value of printAverageGrade ? See this simple example:

> function foo() { console.log("hello"); }
<- undefined
> foo()
  hello
<- undefined

The two undefined are from the console trying to print the return value of the immediate command, and if we try this instead:

> function foo() { console.log("hello"); return "defined"; }
<- undefined
> foo()
  hello
<- "defined"

Specifically, your sample code uses:

console.log(printAverageGrade(students3));

Since printAverageGrade() returns nothing, the console logs undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM