简体   繁体   中英

Creating a multple choice quiz “game”

Some background: I am a near-total beginner learning to write HTML/CSS/JavaScript in my spare time. Please be gentle. :)

A friend of mine, a professional programmer, put together a little project for me to work on in my spare time.

I am creating a quiz game that asks the user to match a randomly-selected English word to one of four Swedish words. I have hit a small hitch: I do not know how to ensure that I am selecting the quiz answers that correspond to the question.

I have written the following variable:

var quiz = [
  {question: 'yes', answers: ['ja', 'förlåt', 'brör', 'samtal'], correct: 0},
  {question: 'sorry', answers: ['att försöka', 'förlåt', 'ingen', 'vår'], correct: 1}
];

And this function:

function engQuestion() {
  return quiz[Math.floor(Math.random() * quiz.length)].question;
}

Within the HTML, I have this:

<div class="question">
  <h2>
    <script>
      document.write(engQuestion());
    </script>
  </h2>
</div>

This is my starting point. I am trying to figure out how I can get the correct set of answers that match my question from the variable. If I write:

return quiz[Math.floor(Math.random() * quiz.length)].answers;

This will obviously give a random set of answers from the entire variable rather than a set of answers from the question's corresponding question array.

Is there a way to return both the questions and answers from the same random number?

The reason I have not found a good answer to this question is that most quiz questions pertain to a test where questions are given in a specific order rather than questions chosen randomly.

Thanks very much for any help.

I realize this seems quite simple to some of you, so I apologize for that.

This might get you started. You may then want to consider whether listing the answers in a list, eg <ul> , would be a good idea. Then, what happens when you click an answer.

 var quiz = [ {question: 'yes', answers: ['ja', 'förlåt', 'brör', 'samtal'], correct: 0}, {question: 'sorry', answers: ['att försöka', 'förlåt', 'ingen', 'vår'], correct: 1} ]; var engQuestion = function() { let randomNumber = Math.floor(Math.random() * quiz.length) let question = quiz[randomNumber].question let answers = quiz[randomNumber].answers document.getElementById('question').innerHTML= question document.getElementById('answers').innerHTML= answers } engQuestion(); 
 <div class="question"> <h2 id="question"> </h2> <h2 id="answers"> </h2> </div> 

I guess assign random number to a var and return quiz question and answer with that variable.

var ran_num = //random number 
return quiz[ran_num].question

The same can be used to return answers. I don't know if this is what you intended.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM