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

时间:2014-10-02 19:27:02

标签: javascript arrays

我正在努力做这个测验。我想要它,所以它产生一个随机的问题。

我有

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"

}, ];

我有

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

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

我刚刚重新加载页面后,问题是随机的。在我回答这个问题之后,又出现了另一个随机问题。 我想要它所以它生成一个随机数。每当我点击回答问题并使用随机生成的数字作为问题编号。

1 个答案:

答案 0 :(得分:0)

当你加载下一个问题时,你正在调用一个名为currentQuestion的函数,该函数不存在。

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

您要做的是设置currentQuestion

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