簡體   English   中英

如何使用 javascript 為我的測驗應用程序生成一個不重復相同問題的隨機問題

[英]How do i generate a random question using javascript for my quiz app which doesn't repeat the same question

我正在嘗試從我的“問題”對象中生成隨機問題,該對象不會重復它本身,但我的測驗應用程序正在重復問題。

如果我的問題不夠清楚,請原諒我。 這是我第一次提出問題或真正使用堆棧溢出,

 let selectedQuestions = []; //creates random index between 0 and the length of any array passed into it const getRandomIndex = (arr) => Math.floor(Math.random() * arr.length); //uses getRandomIndex to generate select a random object from and array. Also checks to see if the random object has been selected, if not, pushes the question to the empty selectedQuestions array and if selected, loops through its own function with a recursion by calling itself until it finds a question that has not already been pushed to the selectedQuestions array. const getRandomObject = (arr) => { const random = getRandomIndex(arr); if (selectedQuestions.includes(random)) { getRandomObject(arr); } selectedQuestions.push(random); console.log("selected questions:", selectedQuestions.length) return arr[random]; //renders the selected array and questions in the correct section of the quiz board. const randomGenerator = () => { const data = getRandomObject(questions); progress.textContent = `Question ${gameState.questionCounter} of ${maxQuestion}` questionBoard.textContent = `Q${gameState.questionCounter}. ${data.question}`; currentCorrectAnswer = data.answer; userAnswer.forEach((answer, index) => { answer.innerHTML = `${alphabet[index]}. ${data.choices[index]}`; }); currentUserAnswer = null; clearAll() gameState.questionCounter++ nextBtn.disabled = true; setDisabledStateForQuizAnswers(false); } }

您在getRandomObject函數中缺少return語句。

if (selectedQuestions.includes(random)) {
  return getRandomObject(arr);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM