随机显示问题数

时间:2018-02-10 09:36:15

标签: javascript html5 web

我想随机显示3个问题中的2个(示例如下)。

我知道它与Math.log()有关,但我无法弄清楚。

编辑:我的意思是Math.random()

我的想法是拥有aprox。 100个问题,每次尝试测验时,只需显示5.这样,每次测验都不同。

以下是JavaScript代码:

(function() {
function buildQuiz() {
  const output = [];

  myQuestions.forEach((currentQuestion, questionNumber) => {
    const answers = [];

    for (var letter in currentQuestion.answers) {
      answers.push(
        `<label>
        <input type="radio" name="question${questionNumber}" value="${letter}">
        ${letter} :
        ${currentQuestion.answers[letter]}
      </label>`
      );
    }

    output.push(
      `<div class="question"> ${currentQuestion.question} </div>
    <div class="answers"> ${answers.join("")} </div>`
    );
  });

  quizContainer.innerHTML = output.join("");
}
const quizContainer = document.getElementById("quiz");
const myQuestions = [{
    question: "Who is the strongest?",
    answers: {
      a: "Superman",
      b: "The Terminator",
      c: "Waluigi, obviously"
    },
    correctAnswer: "c"
  },
  {
    question: "What is the best site ever created?",
    answers: {
      a: "SitePoint",
      b: "Simple Steps Code",
      c: "Trick question; they're both the best"
    },
    correctAnswer: "c"
  },
  {
    question: "Where is Waldo really?",
    answers: {
      a: "Antarctica",
      b: "Exploring the Pacific Ocean",
      c: "Sitting in a tree",
      d: "Minding his own business, so stop asking"
    },
    correctAnswer: "d"
  },

];

1 个答案:

答案 0 :(得分:0)

假设您有一个大小为3的 <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <div class="way_icon"> <h3>jfkfjfjr<i class="fa fa-cog"></i></h3> <a href="#"><i class="fa fa-cog"></i></a> </div>数组,并且您想从中随机选择2个问题。您可以使用myQuestions从数组中选择随机索引。对于大小为3的数组,您可以按如下方式执行此操作:

Math.random()

您可以调用它两次以获得两个随机索引,您可以询问与这些索引相对应的问题。对于更大的问题集,您可以循环执行此随机选择。