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

如何解决JavaScript测验应用中的分数无限累加循环问题

解决测验分数累加问题

核心原因

你的score变量是全局声明的,每次点击「显示结果」按钮调用show()函数时,都会在之前的分数基础上继续累加,无法重新计算当前答题的真实分数。

修复方案

只需在show()函数执行开始时重置分数为0,或者直接将score变量移到函数内部声明,确保每次调用函数都重新初始化分数:

修改后的代码

function show() {
  // 每次计算前重置分数为0
  var score = 0;

  // Q1判断
  const correctAnswer1 = document.getElementById("q1_a2");
  if (correctAnswer1.checked) {
    score++;
    alert("Q1 correct answer");
  } else {
    alert("Q1 wrong answer");
  }

  // Q2判断
  const correctAnswer2 = document.getElementById("q2_a3");
  if (correctAnswer2.checked) {
    score++;
    alert("Q2 correct answer");
  } else {
    alert("Q2 wrong answer");
  }

  // Q3判断(原代码误用了q4的ID,这里修正为q3的正确选项ID,需根据实际情况调整)
  const correctAnswer3 = document.getElementById("q3_a4");
  if (correctAnswer3.checked) {
    score++;
    alert("Q3 correct answer");
  } else {
    alert("Q3 wrong answer");
  }

  // Q4判断
  const correctAnswer4 = document.getElementById("q4_a4");
  if (correctAnswer4.checked) {
    score++;
    alert("Q4 correct answer");
  } else {
    alert("Q4 wrong answer");
  }

  alert("your score is: " + score);
}

额外优化说明

  1. 原代码中questionAnswer1/2/3/4变量重复赋值,无实际作用,可直接删除以减少冗余。
  2. 原代码中Q3的正确选项误用了q4_a4,属于笔误,需修正为对应Q3的正确选项ID,否则Q3的分数判断会出错。
  3. 使用const声明无需重新赋值的变量(如正确选项元素),更符合现代JavaScript规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:45:36