简体   繁体   English

如何生成随机数以从数组中获取随机对象

[英]How to generate a random number to get random object from array

I have this quiz I am trying to make. 我正在尝试做这个测验。 I want it so it generates a random question. 我想要它,因此它产生一个随机问题。

I have 我有

var quiz = [{
  "question": "Question 1: Who is Megatron", // Question 1
  "choices": [
    "Brandon Marshall",
    "Larry Fitzgerald",
    "Robert Griffin III",
    "Calvin Johnson"
  ],
  "correct": "Calvin Johnson"

}, {
  "question": "Question 2: Which player has won the most Superbowls", // Question 2
  "choices": [
    "Eli Manning",
    "Peyton Manning",
    "Aaron Rodgers",
    "Tom Brady"
  ],
  "correct": "Tom Brady"

}, ];

and I have 我有

var randomNumber =Math.floor(Math.random()*3);
var currentQuestion = (randomNumber);

if(currentQuestion < quiz.length - 1){
    currentQuestion(randomNumber);
    questionsDone++;
    loadQuestion();
} else {
    showFinalResults();
}

After I freshly reload the page, the question is random. 重新刷新页面后,问题是随机的。 After I answer that question, a another random question doesn't appear. 在我回答了这个问题之后,没有出现另一个随机问题。 I want it so it generates a random number. 我想要它,以便生成一个随机数。 every time I hit answer a question and use the randomly generated number as the question number. 每次我回答一个问题并使用随机生成的数字作为问题编号。

When you load the next question your calling a function called currentQuestion that does not exist. 当您加载下一个问题时,将调用不存在的名为currentQuestion的函数。

        //if we're not on last question, increase question number
            if(currentQuestion < quiz.length - 1){
                currentQuestion(Math.random()*4);
                questionsDone++;
                loadQuestion();
            }

What you will want to do is set currentQuestion 您将要设置的是currentQuestion

        //if we're not on last question, increase question number
            if(currentQuestion < quiz.length - 1){
                currentQuestion = Math.random()*4;
                questionsDone++;
                loadQuestion();
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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