【发布时间】:2022-11-19 01:51:25
【问题描述】:
我正在创建一个测验,我尝试随机排列答案,但其中一个答案不断重复。最多 4 次,有时甚至 4 次(我总共有 4 个答案)。我的项目截止日期很快,请帮助我。先感谢您
`
const questions = [{
question: "What is the name of Ellie's mom?",
answer: ["Jessica", "Monica", "Anna", "Tess"],
correct: "3",
},
{
question: "Around how old is Joel in The Last of Us Part II?",
answer: ["40s", "50s", "60s", "70s"],
correct: "2",
},
{
question: "What is Manny's rank in the WLF?",
answer: ["Sergeant", "Captain", "Lieutenant", "Corporal"],
correct: "3",
},
{
question: "What item does Ellie keep of Sam's that can be seen in her room at the start of The Last of Us Part II?",
answer: ["PS3", "Toy robot", "Cassette player", "Animals of the Past book"],
correct: "2",
},
{
question: "Which game does NOT get referenced in The Last of US Part II?",
answer: ["Deus Ex", "God of War", "Jak and Daxter", "Crash Bandicoot"],
correct: "2",
}
];
/* Getting elements from the DOM */
let headerContainer = document.getElementById("header");
let listContainer = document.getElementById("list");
let submitBtn = document.getElementById("submit");
let startBtn = document.getElementById("start");
let quiz = document.getElementById("quiz");
let score = 0;
let questionIndex = 0;
startBtn.onclick = function () {
startBtn.classList.add("hidden");
quiz.classList.remove("hidden");
document.getElementById("description").classList.add("hidden");
};
function clearPage() {
headerContainer.innerHTML = "";
listContainer.innerHTML = "";
}
clearPage();
showQuestion();
submitBtn.onclick = checkAnswer;
/*A function to show questions*/
function showQuestion() {
/*Show a question*/
let headerTemplate = `<h2 class="title">%title%</h2>`;
let title = headerTemplate.replace('%title%', questions[questionIndex].question);
headerContainer.innerHTML = title;
/*Show answers*/
let answerNumber = 1;
for (var item of questions[questionIndex].answer) {
const questionTemplate = `<li>
<label>
<input value="%number%" type="radio" class="answer" name="answer">
<span>%answer%</span>
</label>
</li>`;
let answers=questions[questionIndex].answer;
let currentIndex = answers.length, randomIndex;
randomIndex = Math.floor(Math.random() * currentIndex);
let answerText = questionTemplate.replace('%answer%', answers[randomIndex]).replace("%number%", answerNumber);
listContainer.innerHTML += answerText;
answerNumber++;
}
let progress = `<p>${questionIndex+1} out of ${questions.length}</p>`;
document.getElementById("progress").innerHTML = progress;
let scoreBoard = `<p>Score: ${score} out of ${questions.length}</p>`;
document.getElementById("score").innerHTML = scoreBoard;
}
`
我尝试了一个 for 循环,并尝试以我在互联网上找到的不同方式对数组进行洗牌,但它们都按照我现在的方式工作。
【问题讨论】:
-
您不确定您是否已经使用过它。
-
我该怎么做?
-
原则上只需要洗牌一次,然后把答案放进去。
标签: javascript arrays for-loop