Javascript 问题不断重复
我通过javascript和HTML进行了随机测试,问题在JSON文件中,但当我运行测试时,它会多次重复一些问题,如何确保没有问题重复Javascript 问题不断重复,javascript,html,json,Javascript,Html,Json,我通过javascript和HTML进行了随机测试,问题在JSON文件中,但当我运行测试时,它会多次重复一些问题,如何确保没有问题重复 function renderQuestion(){ let index = Math.floor(Math.random() * availableQuestions.length); runningQuestion = availableQuestions[index]; availableQuestions.pop(index); let q = ques
function renderQuestion(){
let index = Math.floor(Math.random() * availableQuestions.length);
runningQuestion = availableQuestions[index];
availableQuestions.pop(index);
let q = questions[runningQuestion];
question.innerHTML = "<p>"+ q.question +"</p>";
qImg.innerHTML = "<img src="+ q.imgSrc +">";
choiceA.innerHTML = q.choiceA;
choiceB.innerHTML = q.choiceB;
choiceC.innerHTML = q.choiceC;
函数renderQuestion(){
让index=Math.floor(Math.random()*availableequestions.length);
runningQuestion=availableQuestions[索引];
AvailableEquistions.pop(索引);
设q=问题[运行问题];
question.innerHTML=“”+q.question+””;
qImg.innerHTML=“”;
choiceA.innerHTML=q.choiceA;
choiceB.innerHTML=q.choiceB;
choiceC.innerHTML=q.choiceC;
}您可以将“索引”推入数组,如
const usedQuestions = [];
然后,当你创建一个新索引时,查看“usedQuestions”索引,不要再使用它们。你正在尝试使用
pop(索引)
。
这是不可能的,因为pop
将始终删除数组中的最后一个元素(并且不接受任何参数!)
改用:
availableQuestions.splice(index, 1); // Remove 1 element at specific index
Array.pop
不接受参数,传递索引在这里没有任何作用。它只是从数组中弹出最后一个元素
假设你有一个问题数组qa=[a,b,c,d,e]
生成一个随机索引(index=2
)并将运行问题设置为该索引(runningQuestion=qa[2]
,=>runningQuestion='c'
)。然后弹出一个元素,数组变成qa=[a,b,c,d]
在下一次函数调用中,仍然可以检索问题c
我建议采取以下方法
pop
,而是使用splice
你可能想洗牌数组,然后将你需要的问题(如果不是全部的话)分成若干个部分。在你挑选完问题后,从数组中移除这些问题。(首先创建数组的浅层副本,以防您的代码支持在不重新加载问题的情况下启动新游戏。)
availableQuestions.pop(index)代码>应可用。拼接(索引1)代码>谢谢@Rojo,修复了:)