You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用数组实现随机抽题及输入答案校验的测验开发疑问

解决测验程序的输入校验问题

嘿,我完全懂你遇到的麻烦——用两个平行数组存题目和答案,随机抽题后要对应上正确答案校验,很容易因为索引没存对或者逻辑对齐出问题。我来给你捋清楚步骤,附上具体的代码示例:

核心问题点

你需要记住当前抽中题目的索引,不能在用户提交答案时重新生成随机数——不然新的随机数会指向另一道题的答案,肯定对不上!

分步解决方案

1. 先确保随机索引生成正确

首先,随机数的生成要基于题目数组的长度,避免数组越界:

// 假设你的题目和答案数组是这样的
const questions = ['question1', 'question2', 'question3'];
const answers = ['answer1', 'answer2', 'answer3'];
let currentQuestionIndex; // 关键:全局/闭包变量存当前题目的索引

2. 抽题逻辑:保存当前索引

写一个抽题函数,生成随机索引后存下来,再返回对应题目:

function getRandomQuestion() {
  // 生成0到题目数组长度-1的随机整数
  currentQuestionIndex = Math.floor(Math.random() * questions.length);
  return questions[currentQuestionIndex];
}

// 页面初始化时显示第一道题
document.getElementById('question-text').textContent = getRandomQuestion();

3. 校验逻辑:用保存的索引拿正确答案

用户提交答案时,用之前存的currentQuestionIndex去答案数组里取正确值,再和用户输入比对:

function validateAnswer() {
  // 获取用户输入,trim掉前后空格避免误判
  const userAnswer = document.getElementById('answer-input').value.trim();
  const correctAnswer = answers[currentQuestionIndex];

  if (userAnswer === correctAnswer) {
    alert('答对啦!👏');
  } else {
    alert(`答错咯,正确答案是:${correctAnswer}`);
  }

  // 答完可以自动刷新下一题
  document.getElementById('question-text').textContent = getRandomQuestion();
  document.getElementById('answer-input').value = ''; // 清空输入框
}

优化建议:用对象数组替代平行数组

其实更稳妥的方式是把题目和答案封装成对象存在一个数组里,这样就不用维护两个平行数组,避免索引错位的风险:

const quizBank = [
  { question: 'question1', answer: 'answer1' },
  { question: 'question2', answer: 'answer2' },
  { question: 'question3', answer: 'answer3' }
];
let currentQuestion;

function getRandomQuestion() {
  const randomIndex = Math.floor(Math.random() * quizBank.length);
  currentQuestion = quizBank[randomIndex];
  return currentQuestion.question;
}

function validateAnswer() {
  const userAnswer = document.getElementById('answer-input').value.trim();
  if (userAnswer.toLowerCase() === currentQuestion.answer.toLowerCase()) {
    // 这里用toLowerCase()忽略大小写,提升用户体验
    alert('太棒了,答对了!');
  } else {
    alert(`不对哦,正确答案是:${currentQuestion.answer}`);
  }
  // 刷新题目
  document.getElementById('question-text').textContent = getRandomQuestion();
  document.getElementById('answer-input').value = '';
}

额外小提示

  • 记得给你的提交按钮绑定validateAnswer函数,比如在HTML里加onclick="validateAnswer()"
  • 如果需要严格区分大小写,就去掉toLowerCase()的处理
  • 可以给输入框加回车触发提交的逻辑,提升交互体验:
document.getElementById('answer-input').addEventListener('keypress', function(e) {
  if (e.key === 'Enter') {
    validateAnswer();
  }
});

内容的提问来源于stack exchange,提问作者rainyclouds25

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:13:56