how to make a Quiz app generate Randome options/answers from an array.

Hello. I’m building a quiz app and I’m trying to run a function that selects random answers from an array quizObject[question]. I tried looping through the array to get the answers but it still didnt work. I also realized that when it works, the answer with the “isTrue” variable will be displayed along with a text of “isTrue”. I definitely need help with this. The codepen is given below, thanks. https://codepen.io/will-ndaji/pen/zYyNjLJ
4 Replies
Choo♚𝕂𝕚𝕟𝕘
You made this more complicated by encoding all correct answers as arrays while all incorrect answers are strings. You also made an object in which the keys are the questions and the values are the answers. A simpler alternative would be:
let quizArray =[
{
question: "In the TV show New Girl, which actress plays Jessica Day?",
answers: ["Zooey Deschanel", "Jennifer Aniston", "Kaley Cuoco", "Alyson Hannigan"],
correctIndex: 0
},
{
question: "What is the largest active volcano in the world?",
answers: ["Mount Loa", "Mount Vesuvius", "Mount Etna", "Mount Batur"],
correctIndex: 0
}
]
let quizArray =[
{
question: "In the TV show New Girl, which actress plays Jessica Day?",
answers: ["Zooey Deschanel", "Jennifer Aniston", "Kaley Cuoco", "Alyson Hannigan"],
correctIndex: 0
},
{
question: "What is the largest active volcano in the world?",
answers: ["Mount Loa", "Mount Vesuvius", "Mount Etna", "Mount Batur"],
correctIndex: 0
}
]
If you consider this to be too verbose, each element of quizArray could be an array instead with element 0 being the question, element 1 being the answers, and element 2 being the index of the correct answer. However, this approach is less favored due to the possibility of mistakes arising from forgetting which index represents which type of data.
Will45
Will4514mo ago
Hello, thanks for your response. I’m still a bit lost as to how to attach the correct answer to the correct index.
Please How would that work?
Choo♚𝕂𝕚𝕟𝕘
When you output the answer choices on the page, it does not matter which one is correct. They all show the same way and you should not hide any clues in the HTML that a cheater would be able to use. For checking the answer, you could either compare the button's innerText to answers[correctIndex] or you could encode the array index as the button's value and compare the button's value to the correctIndex.
Will45
Will4514mo ago
Alright, I’ll try this, thanks for your help!
Want results from more Discord servers?
Add your server