function question1(){
if(sessionStorage.quizCounter == 0){
var qa0 = qs[Math.floor(Math.random() * 19)];
document.getElementById('questions_container').innerHTML = qa0[0]
for (let i = 1; i <= 3; i++) {
document.getElementById('answers_container').innerHTML += qa0[Math.floor((Math.random() * 2))+1];
}
}
}
那是我的函数,它应该将数组中的第一项放在有效的 a<div id="questions_container">
中,但第二部分 - for 循环 - 不起作用。
for 循环应该将最后 3 个项目随机粘贴到<div id="answers_container">
. 我不知道如何超越这个想法。就目前而言,它打印了我不想要的重复项。
qa0[0] 始终是个问题。qa0[1, 2, 3] 总是答案。qa0[] 始终包含 4 个项目。我需要第一个项目始终在 qa0[0] 上。
我想以最简单的方式回答这个问题。
如果您不需要担心位置,您可以随机化数据,然后从末尾删除 N 项。
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}
这将打乱你的数组,基本上是随机化它。然后,您可以将项目从末尾弹出
function randomitems(arr, returnedCount){
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}
const clonedData = arr.slice()
shuffle(clonedData)
if ( returnedCount === undefined) return clonedData;
return clonedData.slice(-1 * returnedCount)
}
这将占用一些空间,因为我不想更改原始对象。
流畅,快速。没有超级复杂的代码。
它将返回一个随机列表,如果基 arr 中有重复项,它将仅返回重复项。否则,它将保持数组项的唯一性。
这将返回一个项目数组,然后您可以循环该列表或使用所需的结果执行任何您特别需要的操作。
如果你想获得超级计算机科学,我也可以提供一个超优化的随机集,但在你的数据集开始变大之前,这在回报方面不太可能看到。
这将在以下情况下为您使用:
// This will link all the questions and possible answers together.
qa0 = [question, ans1, ans2, ans3, ans4].
// The next step is that you need to shuffle the answers.
tmpVar = [].concat(qa0[0], randomizeItems(qa0.slice(1))); // no number will just return the shuffled set.
qa0 = tmpVar; // You could likely just not even use this tmpVar and just do assignment if you really wanted to.
这样,qa0 的问题将是 0 索引,之后的所有项目都将被打乱。所以它看起来像:qa0 = [ question, ans3, ans1, ans2, ans4];
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句