I need to make my code print out on 5 lines [name] + "’s number grade is " + [value] + "and letter grade is a " + [grade] + ‘
‘. [name], [value], and [grade] are in a ‘5 array’ array. I need to do this without using document.write() so I’ve turned to innerHTML. However it’s now only doing the sentence once for the last info on the array.
Here’s what my code looks like now.
//create an array of 5 arrays
let studentsGrade = [
['David', 80],
['Victor', 77],
['Tracey', 55],
['Jason', 95],
['Raymond', 69]
];
//each inner array should contain a name and a number grade
//create a function called getGrade with a parameter of value
//inside the function, create an if/else statement that accounts for grades and values from F to A
function getGrade(value) {
if (value>=90){
return "A";
}
else if(value>=80){
return "B";
}
else if(value>=70){
return "C";
}
else if(value>=60){
return "D";
}
else{
return "F";
}
}
//create a for loop that iterates through the length of the students array and increments by 1 with each loop
//inside the for loop, use a method of your choice (NOT document.write()) to output a string of text that reads like the following example:
//David's number grade is 80 and letter grade is a B
for(var i=0; i<studentsGrade.length; i++){
var name=studentsGrade[i][0]
var value=studentsGrade[i][1]
grade=getGrade(value);
result.innerHTML = name + "'s number grade is " + value + " and letter grade is a " + grade + '<br>';
}
Here’s a comparison of results. The top is the desired result, the bottom is what I got:
Here’s what it’s supposed to look like at the end:
Here’s what is looks like right now:
I’d appreciate any help. I’m very new to javascript, and posting questions to this site, and could really use some guidance
2
Answers
You are setting innerHTML of the same element
result
. Every iteration in the loop set the innerHTML, overriding the previous value. That’s why only the last iteration of the loop appeared. You should combine all the results in a string and then set innerHTML. For example:@ZeyarPaing got it in a nutshell!
In case you are interested, here is another way of coding it: