繁体   English   中英

从 JavaScript 数组 Quizz App 中获取 40 个随机值。 我在另一个文件 questions.js 中有 3000 个问题,我想随机得到 40 个问题

[英]Getting a 40 random values from a JavaScript array, Quizz App. I have in another file questions.js 3000 questions, I want to get random 40 questions

我想从 questions.js 中获得独特的随机 40 个问题,任何人都有建议。

//show Questions from array 
function showQuetions(index) {
  const que_text = document.querySelector(".que_text");

  //question tag add questions from another file
  let que_tag = '<span>' + questions[index].numb + ". " + questions[index].question + '</span>';
  let option_tag = '<div class="option"><span>' + questions[index].options[0] + '</span></div>' +
    '<div class="option"><span>' + questions[index].options[1] + '</span></div>' +
    '<div class="option"><span>' + questions[index].options[2] + '</span></div>' +
    '<div class="option"><span>' + questions[index].options[3] + '</span></div>';
  que_text.innerHTML = que_tag;
  option_list.innerHTML = option_tag;

  const option = option_list.querySelectorAll(".option");

  for (i = 0; i < option.length; i++) {
    option[i].setAttribute("onclick", "optionSelected(this)");

  }
}

有多种方法可以做到这一点:

混洗数组

第一种方法是打乱数组并回答前 40 个问题。

您可以编写一个非常简单的方法来调整您的数组How can I shuffle an array

随机元素

您还可以采用 40 个随机元素(通过采用0和您所拥有的问题数量之间的随机整数,然后从数组中删除这些问题。

在执行此操作之前,请务必对数组进行深拷贝

copy = Object.assign([],questions)

然后,不要忘记从数组中删除问题以确保没有两次相同的问题

这是一个带有两个示例的狙击手:

 /** * Shuffles array in place. * @param {Array} a items An array containing the items. * From https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array */ function shuffle(a) { var j, x, i; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; } const nbQuestions = 2 const questions = ["question 1","question 2","question 3","question 4","question 5","question 6"] //method 1 //deep copy let method1Questions = Object.assign([],questions) shuffle(method1Questions) let randomQuestions1 = method1Questions.slice(0,nbQuestions) console.log(randomQuestions1) //method 2 //deep copy let method2Questions = Object.assign([],questions) let randomQuestions2 = [] for (let i=0; i < nbQuestions; i++){ //random int let questionIndex = Math.floor(Math.random() * method2Questions.length) randomQuestions2.push(method2Questions[questionIndex]) method2Questions.splice(questionIndex,1) } console.log(randomQuestions2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM