简体   繁体   中英

How can I use the Math.random() function to randomize a series of test questions?

I wrote a program which asks the user a series of questions and determines whether the answer entered by the user is correct or incorrect. Example:

var questionsCorrect = 0
var question1 = prompt("question 1");
if (question1.toLowerCase() === "answer 1") {
    question1 = true;
    questionsCorrect += 1;
    alert("Correct");
} else {
    question1 = false;
    alert("Incorrect");
}

var question2 = prompt("question 2");
if (question2.toLowerCase() === "answer 2") {
    question2 = true;
    questionsCorrect += 1;
    alert("Correct");
} else {
    question2 = false;
    alert("Incorrect");
}
...

I plan on displaying how many questions the user answered correctly after all of the questions are asked. Suppose the code goes on this way until question10. how would I use the Math.random() function so that the questions are asked in random order?

This can help you get started.

https://jsfiddle.net/wwnzk6z9/1/

Psuedo-code explanation:

  1. Define an array of questions
  2. Shuffle the array using a custom function ( source )
  3. Keep track of the current index of the array so that you know which question the test taker should be presented with next and also to know when the test taker is done.
  4. Store the answer in the answer array (not coded).

Code:

var questions = [
  'question 1',
  'question 2',
  'question 3',
  'question 4',
  'question 5',
  'question 6',
  'question 7',
  'question 8',
  'question 9',
  'question 10'
]

shuffle(questions)

var index = 0

// assign to window for jsFiddle. You won't need to do this in your code.
window.question = function() {
  if (index === 10) {
    alert('Complete!')
    return;
  }
  alert(questions[index])
  index++
}

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

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