为了账号安全,请及时绑定邮箱和手机立即绑定

尝试以随机顺序显示 JavaScript 测验的问题

尝试以随机顺序显示 JavaScript 测验的问题

婷婷同学_ 2021-06-29 13:49:00
我从这个网站https://www.sitepoint.com/simple-javascript-quiz/借用了一个测验的代码,问题是,我试图让问题以随机顺序显示在屏幕上,而不是在每次都一样的顺序。我尝试了多种方法,但似乎都不起作用,因此非常感谢您的帮助。我猜解决方案在于这个函数,但我不完全确定要修改什么。function buildQuiz() {// we'll need a place to store the HTML outputconst output = [];// for each question...myQuestions.forEach((currentQuestion, questionNumber) => {// we'll want to store the list of answer choicesconst answers = [];// and for each available answer...for (letter in currentQuestion.answers) {  // ...add an HTML radio button  answers.push(    `<label>       <input type="radio" name="question${questionNumber}" value="${letter}" id="botones">        ${letter} :        ${currentQuestion.answers[letter]}     </label>`  );}// add this question and its answers to the outputoutput.push(  `<div class="slide">     <div class="question"> ${currentQuestion.question} </div>     <div class="answers"> ${answers.join("")} </div>   </div>`);});  // finally combine our output list into one string of HTML and put it on the page quizContainer.innerHTML = output.join(""); }
查看完整描述

2 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

您可以使用Math.random:


var questions = ['A','B','C','D','E']

var getRandomQuestion = (questions) => questions.pop(Math.floor(Math.random() * Math.floor(questions.length)));


console.log(getRandomQuestion(questions));

console.log(getRandomQuestion(questions));

console.log(getRandomQuestion(questions));

console.log(getRandomQuestion(questions));


查看完整回答
反对 回复 2021-07-15
?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

在继续之前先打乱问题数组。


var myQuestions = ['A','B','C','D','E']

function shuffle(array) {

  array.sort(() => Math.random() - 0.5);

}

shuffle(myQuestions);

console.log(myQuestions);


查看完整回答
反对 回复 2021-07-15
  • 2 回答
  • 0 关注
  • 176 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信