I am trying out a simple quiz application in JavaScript. I have array of questions object and when I loop through the array and print out the questions it says undefined on the first one but second one is printing the questions to the console.log. Any knows whats happening here.
Thanks.
var questions =
[
{
questions: "What color is of milk?",
choices: ["White", "Blue", "Brown", "Red"],
answer: 0
},
{
question: "What is Tallest Building in the world?",
choices: ["Eifle Tower","Burg Khalifa", "Shenghai Tower" ],
answer: 1
}
];
for ( var i = 0; i < questions.length; i++ ) {
question = questions[i].question;
choices = questions[i].choices;
answer = questions[i].answer;
console.log ( question );
console.log ( choices );
console.log ( answer );
}
asked Jun 7, 2016 at 9:06
J Akhtar
6672 gold badges9 silver badges27 bronze badges
1 Answer 1
Shouldn't questions: "What color is of milk?", be question: "What color is of milk?",
This works fine.
var questions =
[
{
question: "What color is of milk?",
choices: ["White", "Blue", "Brown", "Red"],
answer: 0
},
{
question: "What is Tallest Building in the world?",
choices: ["Eifle Tower","Burg Khalifa", "Shenghai Tower" ],
answer: 1
}
];
for ( var i = 0; i < questions.length; i++ ) {
question = questions[i].question;
choices = questions[i].choices;
answer = questions[i].answer;
console.log ( question );
console.log ( choices );
console.log ( answer );
}
answered Jun 7, 2016 at 9:08
phreakv6
2,1651 gold badge11 silver badges11 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
J Akhtar
upvoted it but can't accept answer in 10 minutes will do after that. I am creating radio buttons for each choices items so the user can choose the answer. createElement, createTextNode and appendChild approach will this be ok for the small program?
phreakv6
Sure, please do. Yes that should do. Do consider jQuery too. You can do this a bit easier with it. Stuff like this
$('<input type="radio" name="blah"/>').appendTo('#myDiv'); where you can leverage your knowledge of html and css to work with the DOM.J Akhtar
just wanna try to avoid jquery coz I'm learning JavaScript and advised to do so until I have good grasp of the language itself.
J Akhtar
just not sure how the first question will be loaded when the page loads and the rest I want to load with click of button namely a next button?
phreakv6
You could write a function
showQuestion() and then do a <body onload="showQuestion()"> and then on the button use a onClick="showQuestion()" to show the next question. Initialise the question_idx in a global variable and increment it everytime showQuestion is called. Try it out and happy coding! |
Explore related questions
See similar questions with these tags.
lang-js