Think this is a simple question but just can' get my head around it;
So have these:
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(name, score) {
gradebook[name]["testScores"].push(score);
},
getAverage: function(name) {
average(gradebook[name]["testScores"]);
}
};
var average = function(array) {
return array.reduce(function(a, b) { return a + b }) / array.length;
};
Have 2 arrays, and gradebook object, want to call gradebook.getAverage("Joseph") and return the average. but this line average(gradebook[name]["testScores"]);
in getAverage function I don't think is working.
When I put the code into node terminal and then do gradebook.getAverage("Joseph");
i get undefined.
If I do average(gradebook["Joseph"]["testScores"]
in the terminal I get the answer I want.
Hopefully this makes sense! thanks
The reason you are getting undefined
from the function call is that they are not returning any value. Change it to this:
addScore: function(name, score) {
return gradebook[name]["testScores"].push(score);
},
getAverage: function(name) {
return average(gradebook[name]["testScores"]);
}
};
You need to return the value from the getAverage
method:
getAverage: function(name) {
return average(gradebook[name]["testScores"]);
}
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.