简体   繁体   中英

How to randomly select an object with a specific property value out of an array

I am creating a timed trivia game that randomly selects a question stored in an object from an array. Currently, I have the program randomly select a question from the array but it will sometimes choose one that has already been chosen. I want my currentQuestion variable to only be an object from the array with questionChosen: false

I have tried a while loop but I don't think I formatted it correctly causing the program to loop infinitely thus not working.

   // This is how objects are stored in the questionsArr
    var q1 = {
       title: "Question 1",
       a1: "answer 1.",
       a2: "answer 2.",
       a3: "answer 3.",
       a4: "answer 4.",
       questionChosen: false,
    };

This is my function that generates a new questions and sets whether they have been chosen to true

   function newQuestion() {
      time = 30;
      var currentQuestion = questionsArr[Math.floor(Math.random() * questionsArr.length)];

     if (intervalId && intervalId >= 0) {
         clearInterval(intervalId);
     }
     if (!clockRunning) {
        clockRunning = true;
     }

     currentQuestion.questionChosen = true;
     intervalId = setInterval(countdown, 1000);
     console.log(intervalId);
     console.log(clockRunning);
     $("#question-box").text(currentQuestion.title);
     $("#a1").text(currentQuestion.a1);
     $("#a2").text(currentQuestion.a2);
     $("#a3").text(currentQuestion.a3);
     $("#a4").text(currentQuestion.a4);
  }

I recommend you rethink your approach: Even if you manage to code it out well, the performance will get worse and worse over time. Just think of a pool of 1000 questions, where 999 have already been answered: You would need to run through your loop as many times as it needs to finally select the last question.

A typical construct would be to have two lists: One has the not-yet asked questions, the other the already-asked ones. When you chose a question you remove it from the one list and append it to the other. Nothing stops you from also having a combined list, if your logic needs that.

You can then easily chose a random question from the "unused" list without any problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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