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

JS quiz应用最后一题出现undefined错误且答案选项不显示问题排查

问题根因

你的bug核心是JavaScript数组使用0基索引,而你的题目索引逻辑是按1基设计的,索引越界导致最后一题读取到undefined值:
你定义了6道题,数组shuffledQuestions的有效索引范围是0~5,但你把currentQuestionIndex的初始值设为1,当你点击下一题到最后一轮时,currentQuestionIndex会累加到6,此时shuffledQuestions[6]为undefined,传入showQuestion函数后无法读取answers属性,自然渲染不出选项。

修复步骤

  1. 修改索引初始值为0
    把代码中变量初始化行:
let shuffledQuestions, currentQuestionIndex = 1, score = 0

修改为:

let shuffledQuestions, currentQuestionIndex = 0, score = 0
  1. 调整面向用户的题号展示逻辑
    因为索引是0基,但展示给用户的题号需要从1开始,修改showQuestion函数中的两行代码:
// 原代码
progressText.innerText = `Question ${currentQuestionIndex} of ${MAX_QUESTIONS}`
progressBarFull.style.width = `${(currentQuestionIndex / MAX_QUESTIONS) * 100}%`
// 修改后
progressText.innerText = `Question ${currentQuestionIndex + 1} of ${MAX_QUESTIONS}`
progressBarFull.style.width = `${((currentQuestionIndex + 1) / MAX_QUESTIONS) * 100}%`
  1. 调整下一题按钮的显示判断逻辑
    修改selectAnswer函数中的判断条件,确保当前是最后一题时不显示下一题按钮:
// 原代码
if (shuffledQuestions.length > currentQuestionIndex) {
// 修改后
if (shuffledQuestions.length > currentQuestionIndex + 1) {

额外优化建议

你目前的跳转逻辑写在incrementScore中,只有用户答对题目才会触发跳转判断,建议把跳转逻辑移到selectAnswer的末尾,无论用户答对答错,选完最后一题都自动跳转到结束页,避免逻辑漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:15:03