【问题标题】:Shuffled answers are repeating in a quiz打乱的答案在测验中重复出现
【发布时间】:2022-11-19 01:51:25
【问题描述】:

我正在创建一个测验,我尝试随机排列答案,但其中一个答案不断重复。最多 4 次,有时甚至 4 次(我总共有 4 个答案)。我的项目截止日期很快,请帮助我。先感谢您

`

const questions = [{
        question: "What is the name of Ellie's mom?",
        answer: ["Jessica", "Monica", "Anna", "Tess"],
        correct: "3",
    },
    {
        question: "Around how old is Joel in The Last of Us Part II?",
        answer: ["40s", "50s", "60s", "70s"],
        correct: "2",
    },
    {
        question: "What is Manny's rank in the WLF?",
        answer: ["Sergeant", "Captain", "Lieutenant", "Corporal"],
        correct: "3",
    },
    {
        question: "What item does Ellie keep of Sam's that can be seen in her room at the start of The Last of Us Part II?",
        answer: ["PS3", "Toy robot", "Cassette player", "Animals of the Past book"],
        correct: "2",
    },
    {
        question: "Which game does NOT get referenced in The Last of US Part II?",
        answer: ["Deus Ex", "God of War", "Jak and Daxter", "Crash Bandicoot"],
        correct: "2",
    }
];

/* Getting elements from the DOM */
let headerContainer = document.getElementById("header");
let listContainer = document.getElementById("list");
let submitBtn = document.getElementById("submit");
let startBtn = document.getElementById("start");
let quiz = document.getElementById("quiz");

let score = 0;
let questionIndex = 0;

startBtn.onclick = function () {
    startBtn.classList.add("hidden");
    quiz.classList.remove("hidden");
    document.getElementById("description").classList.add("hidden");
};

function clearPage() {
    headerContainer.innerHTML = "";
    listContainer.innerHTML = "";
}

clearPage();
showQuestion();
submitBtn.onclick = checkAnswer;

/*A function to show questions*/
function showQuestion() {
    /*Show a question*/
    let headerTemplate = `<h2 class="title">%title%</h2>`;
    let title = headerTemplate.replace('%title%', questions[questionIndex].question);
    headerContainer.innerHTML = title;

    /*Show answers*/
    let answerNumber = 1;
    for (var item of questions[questionIndex].answer) {
        const questionTemplate = `<li>
        <label>
           <input value="%number%" type="radio" class="answer" name="answer">
           <span>%answer%</span>
        </label>
        </li>`;

        
        let answers=questions[questionIndex].answer;
        let currentIndex = answers.length,  randomIndex;
        randomIndex = Math.floor(Math.random() * currentIndex);
                
        let answerText = questionTemplate.replace('%answer%', answers[randomIndex]).replace("%number%", answerNumber);

        listContainer.innerHTML += answerText;
        answerNumber++;
    }
    let progress = `<p>${questionIndex+1} out of ${questions.length}</p>`;
    document.getElementById("progress").innerHTML = progress;

    let scoreBoard = `<p>Score: ${score} out of ${questions.length}</p>`;
    document.getElementById("score").innerHTML = scoreBoard;
}

`

我尝试了一个 for 循环,并尝试以我在互联网上找到的不同方式对数组进行洗牌,但它们都按照我现在的方式工作。

【问题讨论】:

  • 您不确定您是否已经使用过它。
  • 我该怎么做?
  • 原则上只需要洗牌一次,然后把答案放进去。

标签: javascript arrays for-loop


【解决方案1】:

您的方法将要求您跟踪您使用的问题。如果你用过它,再拉一个。可以做到,但还有更好的方法。

最简单的方法,生成 lis 数组并将其洗牌。您还应该以正确的方式使用模板文字。您正在通过更换琴弦来重新发明它们。它已经这样做了!

function shuffle(array) {
  let currentIndex = array.length,
    randomIndex;

  // While there remain elements to shuffle.
  while (currentIndex != 0) {

    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]
    ];
  }

  return array;
}


const questions = [{
    question: "What is the name of Ellie's mom?",
    answer: ["Jessica", "Monica", "Anna", "Tess"],
    correct: "3",
  },
  {
    question: "Around how old is Joel in The Last of Us Part II?",
    answer: ["40s", "50s", "60s", "70s"],
    correct: "2",
  },
  {
    question: "What is Manny's rank in the WLF?",
    answer: ["Sergeant", "Captain", "Lieutenant", "Corporal"],
    correct: "3",
  },
  {
    question: "What item does Ellie keep of Sam's that can be seen in her room at the start of The Last of Us Part II?",
    answer: ["PS3", "Toy robot", "Cassette player", "Animals of the Past book"],
    correct: "2",
  },
  {
    question: "Which game does NOT get referenced in The Last of US Part II?",
    answer: ["Deus Ex", "God of War", "Jak and Daxter", "Crash Bandicoot"],
    correct: "2",
  }
];

/* Getting elements from the DOM */
let headerContainer = document.getElementById("header");
let listContainer = document.getElementById("list");
let questionIndex = 0;

function showQuestion() {

  headerContainer.innerHTML = `<h2 class="title">${questions[questionIndex].question}</h2>`;

  const lis = questions[questionIndex].answer.map((answer, index) =>
    `<li>
        <label>
           <input value="${index}" type="radio" class="answer" name="answer">
           <span>${answer}</span>
        </label>
       </li>`);

  listContainer.innerHTML = shuffle(lis).join('');

}

showQuestion();
<h2 id="header"></h2>
<ul id="list"></ul>

【讨论】:

    【解决方案2】:

    您需要以某种方式保存(或知道)已经出现的答案。 否则,您将创建一个随机数(在您的for循环) 可能与上一次迭代相同。

    您可以创建一个包含 4 个位置的数组(答案 1、2、3、4):[1、2、3、4]

    let arrayCurrentIndex = [];
    
    for (let index = 0; index < questions[questionIndex].answer.length; index++) {
        arrayCurrentIndex.push(index);
    }
    

    然后在你的for循环你可以从新数组arrayCurrentIndex中得到一个随机数

    randomIndex = arrayCurrentIndex[Math.floor(Math.random() * arrayCurrentIndex.length)];
    

    现在您有了索引,我们需要删除arrayCurrentIndex中相同数量的randomIndex。为了防止 randomIndex 的下一次迭代环形从和以前一样

    let indexToRemove = arrayCurrentIndex.indexOf(randomIndex);
    arrayCurrentIndex.splice(indexToRemove, 1);
    

    像这样:

    let arrayCurrentIndex = [];
    
    for (let index = 0; index < questions[questionIndex].answer.length; index++) {
        arrayCurrentIndex.push(index);
    }
    
    /*Show answers*/
    let answerNumber = 1;
    for (var item of questions[questionIndex].answer) {
        const questionTemplate = `<li>
        <label>
            <input value="%number%" type="radio" class="answer" name="answer">
            <span>%answer%</span>
        </label>
        </li>`;
    
        
        let answers=questions[questionIndex].answer;
    
        randomIndex = arrayCurrentIndex[Math.floor(Math.random() * arrayCurrentIndex.length)];
    
        // Remove use number (randomIndex) from arrayCurrentIndex
        let indexToRemove = arrayCurrentIndex.indexOf(randomIndex);
        arrayCurrentIndex.splice(indexToRemove, 1);
                
        let answerText = questionTemplate.replace('%answer%', answers[randomIndex]).replace("%number%", answerNumber);
    
        listContainer.innerHTML += answerText;
        answerNumber++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 2016-04-23
      • 1970-01-01
      • 2020-04-06
      相关资源
      最近更新 更多