samedi 12 février 2022

choose random index from array and show it once [duplicate]

hey I have a quiz I made with JavaScript and I have an array for questions I want to randomly show questions from the array but I don't want the questions to repeat themselves so I created another array for used questions and every question that is asked is in the array. and I tried to check if the new question is in the array before it gets printed but it doesn't work how can I randomly show questions from the array without repeating them?

function randomize() {
    let random = Math.floor(Math.random() * questions.length);
    return random;
}
let usedQuestions = [10];

submit.addEventListener("click", function(){
    if(questionNumber == questions.length - 1){
        question.style.display = "none";
        answer.style.display = "none";
        submit.style.display = "none";

        card.style.display = "block";
        score.innerText = "Your score is " + points + "/" + questions.length * 10;
        //stop the function from running
        return;
    }
    let userAnswer = document.getElementById("answer").value;
    if(userAnswer == answers[questionNumber]){
        points +=10;
        console.log("correct");
    }   
    else{
        console.log("incorrect" + " " + "the correct answer is " + answers[questionNumber]);
        //if(points == 10){
            //points = 0;
        //}
    }
    //in the else I check if the user have more than 10 points and if so I decrement the points by 10 but id no then I set the points to 0
    questionNumber++;
    answer.value = "";
    counter++;

    
    usedQuestions[questionNumber] = questions[randomize()];
    function check(){
    for (let i = 0; i < usedQuestions.length; i++) {
        if(usedQuestions[i] == randomize()){
            randomize();
            check();
        }     
    }
    }

check();
    //question.innerText = questions[questionNumber];
    question.innerText = questions[randomize()];
});



Aucun commentaire:

Enregistrer un commentaire