2014-10-02 62 views
0

我有这个测验我正在尝试。我想要它,所以它会产生一个随机问题。如何生成一个随机数字以获得数组中的随机对象

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(); 
} 

我刚刚刷新页面后,这个问题是随机的。在我回答这个问题后,另一个随机问题不会出现。 我想要它,所以它会生成一个随机数。每次我回答一个问题并使用随机生成的数字作为问题编号。

+3

你做些什么,使问题你的答案后,显示是什么? – 2014-10-02 19:30:27

+0

@LeshaOgonkov整个代码是http://codepaste.net/m55e4b – Phil 2014-10-02 19:33:13

+0

@Phil查看[这个问题](http://stackoverflow.com/q/988363/2033671)问题的一些提示调试javascript – 2014-10-02 19:48:21

回答

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(); 
      }