i'm new to programming and stack overflow, so pardon my gibberish .Please i am having issues printing out the last three arrays. it prints out just the last element in the array.But when i use the console.log it prints all the elements out.I hope i am making sense. Kindly help. Any help will be appreciated. Thanks
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<h1>Score Sheet</h1>
<script type="text/javascript">
var candidateName = [];
var candidates = 0;
var moreCandidates = "y";
while (moreCandidates == "y"){
candidateName.push(prompt("Enter candidate name"));
var noOfSubjects = prompt("How many subjects are you offering?");
for(i = 1; i <= noOfSubjects; i++){
var subName = [];
var scores = [];
var unit = [];
subName.push(prompt("What is the subject name?"));
console.log(subName);
scores.push(prompt("Enter your subject score"));
console.log(scores);
unit.push(prompt("Enter your subject unit"));
console.log(unit);
}
moreCandidates = prompt("Do you want to add more candidates? y/n");
candidates++
}
document.write("Number of candidates is" + " " + candidates);
document.write("<br/>");
document.write(candidateName);
document.write("<br/>");
document.write(noOfSubjects);
document.write("<br/>");
document.write(subName);
document.write("<br/>");
// document.write(scores);
// document.write("<br/>");
// document.write(unit);
</script>
2 Answers 2
The problem is you are resetting the arrays for each loop iteration so they will only ever contain one value. Declare them outside the loop instead.
Don't forget var for i otherwise it will be defined on the global scope and I would say consider a proper interface rather than using prompt() to get the values you are after it will provide a better user experience.
var subName = [];
var scores = [];
var unit = [];
for(var i = 1; i <= noOfSubjects; i++){
subName.push(prompt("What is the subject name?"));
console.log(subName);
scores.push(prompt("Enter your subject score"));
console.log(scores);
unit.push(prompt("Enter your subject unit"));
console.log(unit);
}
If you want to use document write you could simply use join() as in
document.write(scores.join(", "))
to print out the array values.
2 Comments
I believe (I haven't tested this) that you must use a loop to use document.write with an array:
for(var i = 0; i < candidateName.length; i++)
{
document.write(candidateName[i]);
}
Have a look at these:
it prints out just the last element in the array.. What is it?