2014-10-02 56 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(); 
      }