gpt4 book ai didi

Javascript 问答游戏 - 从数组中的八个问题中随机抽取四个问题

转载 作者:行者123 更新时间:2023-12-03 02:05:26 24 4
gpt4 key购买 nike

我正在尝试创建一个 JavaScript 测验。我遵循了这个 YouTube 教程:1 , 2 。我想做的是从数组中的 8 个中随机选择 4 个问题。我的 JavaScript 代码是:

var currentQuestion = 0;
var score = 0;
var totQuestions = questions.length;

var container = document.getElementById("quizContainer");
var questionEl = document.getElementById("question");
var opt1 = document.getElementById("opt1");
var opt2 = document.getElementById("opt2");
var opt3 = document.getElementById("opt3");
var opt4 = document.getElementById("opt4");
var nextButton = document.getElementById("nextButton");
var resultCont = document.getElementById("result");

function loadQuestion (questionIndex) {
var q = questions[questionIndex];
questionEl.textContent = (questionIndex + 1) + ". " + q.question;
opt1.textContent = q.option1;
opt2.textContent = q.option2;
opt3.textContent = q.option3;
opt4.textContent = q.option4;
};

function loadNextQuestion () {
var selectedOption = document.querySelector("input[type=radio]:checked");
if(!selectedOption) {
alert("Please select your answer!");
return;
}
var answer = selectedOption.value;
if(questions[currentQuestion].answer == answer) {
score ++;
}
selectedOption.checked = false;
currentQuestion++;
if(currentQuestion == totQuestions - 1) {
nextButton.textContent = "Finish";
}
if(currentQuestion == totQuestions) {
container.style.display = "none";
resultCont.style.display = "";
resultCont.textContent = "Your Score: " + score;
return;
}
loadQuestion(currentQuestion);
}

loadQuestion(currentQuestion);

我尝试使用 math.random() 但我唯一能做的就是生成随机数,而不是从数组中生成随机问题。
包含问题的数组如下所示:

{
"question": "This is question 3",
"option1": "A",
"option2": "B",
"option3": "C",
"option4": "D",
"answer": "2"
},
{
"question": "This is question 4",
"option1": "A",
"option2": "B",
"option3": "C",
"option4": "D",
"answer": "1"
}

提前谢谢您。

最佳答案

下面的代码将从数组中随机获取一个项目:

var randomQ = questions[Math.round((Math.random()*questions.length)+1)];

关于Javascript 问答游戏 - 从数组中的八个问题中随机抽取四个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com