2017-02-14 36 views
-2

我寫了一個程序,詢問用戶一系列問題,並確定用戶輸入的答案是正確還是不正確。示例:如何使用Math.random()函數隨機化一系列測試問題?

var questionsCorrect = 0 
var question1 = prompt("question 1"); 
if (question1.toLowerCase() === "answer 1") { 
    question1 = true; 
    questionsCorrect += 1; 
    alert("Correct"); 
} else { 
    question1 = false; 
    alert("Incorrect"); 
} 

var question2 = prompt("question 2"); 
if (question2.toLowerCase() === "answer 2") { 
    question2 = true; 
    questionsCorrect += 1; 
    alert("Correct"); 
} else { 
    question2 = false; 
    alert("Incorrect"); 
} 
... 

我打算在顯示所有問題後,用戶正確回答了多少個問題。假設代碼一直持續到問題10。我將如何使用Math.random()函數以便隨機順序詢問問題?

+1

[生成隨機兩個數字之間用JavaScript號](可能的重複http://stackoverflow.com/questions/4959975/generate-random-number-between-two-數字在JavaScript) –

+0

也許是更聰明的學習功能的第一個概念,以防止重複的代碼。那麼我建議看看數組。 –

回答

0

這可以幫助您開始。

https://jsfiddle.net/wwnzk6z9/1/

僞代碼的解釋:

  1. 定義的問題的陣列
  2. 使用自定義函數洗牌陣列(source
  3. 跟蹤該陣列的當前索引的這樣你就可以知道下一個考生應該提出哪個問題,並且知道考生何時完成考試。
  4. 將答案存儲在答案數組中(未編碼)。

代碼:

var questions = [ 
    'question 1', 
    'question 2', 
    'question 3', 
    'question 4', 
    'question 5', 
    'question 6', 
    'question 7', 
    'question 8', 
    'question 9', 
    'question 10' 
] 

shuffle(questions) 

var index = 0 

// assign to window for jsFiddle. You won't need to do this in your code. 
window.question = function() { 
    if (index === 10) { 
    alert('Complete!') 
    return; 
    } 
    alert(questions[index]) 
    index++ 
} 

function shuffle(array) { 
    var currentIndex = array.length, temporaryValue, randomIndex; 

    // While there remain elements to shuffle... 
    while (0 !== currentIndex) { 

    // Pick a remaining element... 
    randomIndex = Math.floor(Math.random() * currentIndex); 
    currentIndex -= 1; 

    // And swap it with the current element. 
    temporaryValue = array[currentIndex]; 
    array[currentIndex] = array[randomIndex]; 
    array[randomIndex] = temporaryValue; 
    } 

    return array; 
}