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

如何将JavaScript测验答案对象的值随机填入选项输入框中

核心问题排查

你当前代码的主要问题有3个:

  1. 遍历所有拉取到的题目时,直接在循环内覆盖题干和选项的内容,循环结束后只会保留最后一道题的内容
  2. 没有将答案对象转换为可遍历的数组,也没有做随机打乱处理
  3. 所有选项统一赋值为vragen[i].answers.object,自然不会生成不同的候选项

解决代码

首先实现通用的数组随机打乱函数(Fisher-Yates洗牌算法,保证随机公平):

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

修改业务逻辑,拆分拉取题目和渲染单题的逻辑:

// 全局变量存储题目列表、当前展示的题目索引
let globalVragen = []
let currentVraagIndex = 0

fetch(myUrl)
  .then(res => res.json())
  .then(loadedQuestions => {
    globalVragen = loadedQuestions
    // 加载完成后渲染第一道题
    renderCurrentVraag()
    startGame()
  })
  .catch(err => console.error(err))

// 渲染当前题目
function renderCurrentVraag() {
  const currentVraag = globalVragen[currentVraagIndex]
  // 渲染题干
  mijnVraag.innerHTML = currentVraag.question
  // 将答案对象转为数组,如果答案有嵌套结构自行调整取值逻辑
  const answerList = Object.values(currentVraag.answers)
  // 打乱答案顺序
  const shuffledAnswers = shuffleArray(answerList)
  // 给选项赋值,默认取前4个选项,隐藏多余的2个选项
  choices.forEach((choice, index) => {
    if (index < 4) {
      choice.parentElement.style.display = 'block'
      choice.innerHTML = shuffledAnswers[index]
    } else {
      choice.parentElement.style.display = 'none'
    }
  })
}

// 切换下一题时调用
function nextVraag() {
  currentVraagIndex++
  if (currentVraagIndex < MAX_VRAGEN) {
    renderCurrentVraag()
  } else {
    // 所有题目作答完成的后续逻辑
    alert('测验已结束')
  }
}

注意事项

  • 如果接口返回的答案对象包含是否正确的标识,转换数组时保留对应字段即可实现后续的答案校验逻辑
  • 你当前HTML里的li元素直接放在div容器中不符合语义规范,建议将外层的#antwoordcontainer从div改为ul标签,避免出现布局兼容问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:36:04