如何随机化question_options数组并以单选按钮展示试题选项?
Got it! You want to randomize your question_options so the correct answer doesn't stay stuck in the same position for every question, then render those options as radio buttons. Let's work through this with practical fixes and improvements for your code.
Step 1: Fix Array Merging & Add Proper Randomization (Fisher-Yates Shuffle)
First, let's clean up your initial array setup (I noticed a small typo where you used test.right_answer instead of your defined right_answer variable). Then, we'll use the Fisher-Yates Shuffle—this is the gold standard for randomizing arrays because it avoids bias that simpler methods (like sort(() => Math.random() - 0.5)) can introduce.
Here's how to implement it:
// Your original answer data const wrongAnswers = [1990, 1991, 1992, 1994]; const rightAnswer = 1993; // No need to wrap in an array unless you have multiple correct answers // Merge correct and wrong answers into a single array let questionOptions = [rightAnswer, ...wrongAnswers]; // Fisher-Yates Shuffle function to randomize the array function shuffleArray(array) { const newArray = [...array]; // Make a copy to avoid mutating the original for (let i = newArray.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [newArray[i], newArray[j]] = [newArray[j], newArray[i]]; } return newArray; } // Get your randomized options const randomizedOptions = shuffleArray(questionOptions);
Step 2: Render Randomized Options as Radio Buttons
Now let's take that randomized array and turn it into functional radio buttons. We'll dynamically create elements and append them to a container in your HTML.
First, add a container to your HTML:
<div id="question-options-container"></div>
Then use this JavaScript to render the radio buttons:
const container = document.getElementById('question-options-container'); const questionName = 'year-question'; // Unique name for the radio group (ensures single selection) randomizedOptions.forEach((option, index) => { // Create radio button const radio = document.createElement('input'); radio.type = 'radio'; radio.name = questionName; radio.value = option; radio.id = `${questionName}-${index}`; // Create label for the radio button const label = document.createElement('label'); label.htmlFor = radio.id; label.textContent = option; // Append both to the container container.appendChild(radio); container.appendChild(label); container.appendChild(document.createElement('br')); // Add line breaks for readability });
Bonus: Track Correct Answers Easily
If you need to verify which option is correct after the user selects one, it's better to store each option with a flag indicating if it's the right answer. This way, even after shuffling, you don't lose track:
// Create an array of objects instead of just values const questionOptionsWithFlags = [ { value: rightAnswer, isCorrect: true }, ...wrongAnswers.map(answer => ({ value: answer, isCorrect: false })) ]; // Shuffle this array instead const randomizedOptionsWithFlags = shuffleArray(questionOptionsWithFlags); // When rendering, you can keep track of the correct flag (useful for validation) randomizedOptionsWithFlags.forEach((option, index) => { const radio = document.createElement('input'); radio.type = 'radio'; radio.name = 'year-question'; radio.value = option.value; radio.id = `year-question-${index}`; // You could add a data attribute if needed: radio.dataset.isCorrect = option.isCorrect; const label = document.createElement('label'); label.htmlFor = radio.id; label.textContent = option.value; container.appendChild(radio); container.appendChild(label); container.appendChild(document.createElement('br')); });
This setup ensures every time the question loads, the options are in a random order, so the correct answer doesn't stay in the same spot. The Fisher-Yates shuffle guarantees a fair randomization, and the object-based approach makes validation straightforward later on.
内容的提问来源于stack exchange,提问作者Daniel ikeobi

