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

JavaScript Quiz项目:数组耗尽时显示Finish按钮的if逻辑修正

问题解决:Quiz题目用完后显示结束按钮

问题描述

我是JavaScript编程新手,正在为课程项目制作包含11道题的Quiz。代码通过quiz.splice(randomNumber, 1)随机抽取问题直至所有题目用完。我希望当数组无元素可splice(所有题目答完)时,显示默认隐藏的'Finish'按钮以结束Quiz。尝试了以下代码但无效:

if (quiz > 0) {
  quiz.splice(randomNumber, 1); //this ensures a question doesn't repeat
} else {
  document.getElementById('endQuiz').style.visibility='visible';
}

完整代码如下:

//variables
var quiz = [];
quiz[0] = new Question("What is the first home console title that featured Waluigi as a playable character?", "Mario Tennis (Nintendo 64)", "Mario Kart 64", "Mario Party 3");
quiz[1] = new Question("Waluigi made his Mario Kart debut in the 2003 Nintendo Gamecube title 'Mario Kart: Double Dash' and has appeared in all but one of the series' subsequent Nintendo console games. Which title was he misisng from? ", "Mario Kart 3DS", "Mario Kart Wii", "Mario Kart 8 (Wii U)");
quiz[2] = new Question("In Mario Party 8, what does Waluigi flaunt for his winning animation?", "A rose", "A trophy", "Nothing");
quiz[3] = new Question("In Mario Kart: Double Dash, what is the name of Waluigi's personal kart?", "Waluigi Racer", "Zipper", "Gold Mantis");
quiz[4] = new Question("Featuring in Mario Kart DS, Mario Kart 3DS, Mario Kart Tour and most recently Mario Kart 8 Deluxe, what is the name of Waluigi's self-titled race course?", "Waluigi Pinball", "Waluigi Stadium", "Waluigi Circuit");
quiz[5] = new Question("Waluigi is traditionally seen as the primary rival to which character?", "Luigi", "Mario", "Wario");
quiz[6] = new Question("What is the traditional colour of Waluigi's undershirt and headwear?", "Purple", "Green", "Yellow");
quiz[7] = new Question("Waluigi is a playable character in which of the following Super Smash Bros series entries?", "Waluigi is not a playable character in these games", "Super Smash Bros for Nintendo 3DS/Wii U", "Super Smash Bros Ultimate");
quiz[8] = new Question("In Mario Kart Tour, as part of the 2021 Halloween Tour, a variant of Waluigi was introdcued as a playable character. What is the nature of this character?", "He's a Vampire", "He's a Werewolf", "He's a Zombie");
quiz[9] = new Question("As a playable character in many of the Mario Golf games, what shot trajectory has Waluigi often been associated with?", "Draw (right to left)", "Fade (left to right)", "Straight");
quiz[10] = new Question("As of November 2022, what is Waluigi's most recent home console video game appearance?", "Mario Strikers: Battle League", "Mario Party Superstars", "Mario Golf: Super Rush");

var answers = [];
var currentScore = 0;

document.addEventListener("DOMContentLoaded", function(){
    document.getElementById('endQuiz').style.visibility='hidden';
    btnProvideQuestion()
    })   
    
//this is the structure of the question
function Question(question,rightAnswer,wrongAnswer1,wrongAnswer2) {
    this.question = question;
    this.rightAnswer = rightAnswer;
    this.wrongAnswer1 = wrongAnswer1;
    this.wrongAnswer2 = wrongAnswer2;
};

//this function ensures that the right answer, as defined in 'function Question', is not always the first displayed answer
function shuffle(o) {
    for(let j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

function btnProvideQuestion() { 
  
  //generates a question and its answers from the available list on a button click
    var randomNumber = Math.floor(Math.random()*quiz.length);
    randomQuestion = quiz[randomNumber]; 
  answers = [randomQuestion.rightAnswer, randomQuestion.wrongAnswer1, randomQuestion.wrongAnswer2];
  shuffle(answers);
    if (quiz > 0) {
  quiz.splice(randomNumber, 1); //this ensures a question doesn't repeat
  } else {
    document.getElementById('endQuiz').style.visibility='visible';
  }

  document.getElementById("question").innerHTML= randomQuestion.question;
  document.getElementById("answerA").value= answers[0];
  document.getElementById("answerA").innerHTML= answers[0];
  document.getElementById("answerB").value= answers[1];
  document.getElementById("answerB").innerHTML= answers[1];
  document.getElementById("answerC").value= answers[2];
  document.getElementById("answerC").innerHTML= answers[2];
}

//check to see if the clicked answer is the correct one
function answerA_clicked() {
  let answerA = document.getElementById("answerA").value;
    checkAnswer(answerA);
}
function answerB_clicked() {
        let answerB = document.getElementById("answerB").value;
  checkAnswer(answerB);
}
function answerC_clicked() {
    let answerC = document.getElementById("answerC").value;
  checkAnswer(answerC);
}

//updates the correct score display
function adjustScore(isCorrect) {
  debugger;
  if (isCorrect) {
    currentScore++;
  } else {
    currentScore+ 0;
  }
  document.getElementById("score").innerHTML = currentScore;
}

//the message that displays when you choose an answer
function checkAnswer(answer) {  
  if (answer == randomQuestion.rightAnswer) {
    alert("Congratulations! You got it right!")
    adjustScore(true);
    btnProvideQuestion();
  } else { 
    alert("That's the wrong answer. Wahhhhhh....");
    adjustScore(false);
    btnProvideQuestion();
  }   
}

错误原因

  1. 数组判断逻辑错误:quiz > 0的写法不严谨,数组和数字比较时会被转换成字符串,非空数组永远满足>0;空数组转成空字符串后"" > 0为false,但此时代码已经执行了randomQuestion = quiz[randomNumber];,而quiz.length为0时randomNumber是0,quiz[0]是undefined,后续访问randomQuestion.question会直接报错,导致代码中断,根本执行不到显示按钮的逻辑。
  2. 执行顺序错误:先获取题目再判断数组长度,会导致数组为空时直接抛出错误,应该先判断数组是否还有元素,再处理抽题和渲染逻辑。

修正方案

修改btnProvideQuestion函数,调整执行顺序,先判断数组长度:

function btnProvideQuestion() { 
  // 先判断是否还有剩余题目
  if (quiz.length > 0) {
    // 生成随机题目索引
    var randomNumber = Math.floor(Math.random()*quiz.length);
    // 用let声明randomQuestion,避免全局变量污染
    let randomQuestion = quiz[randomNumber]; 
    answers = [randomQuestion.rightAnswer, randomQuestion.wrongAnswer1, randomQuestion.wrongAnswer2];
    shuffle(answers);

    // 移除已抽取的题目
    quiz.splice(randomNumber, 1);

    // 渲染题目和选项
    document.getElementById("question").innerHTML= randomQuestion.question;
    document.getElementById("answerA").value= answers[0];
    document.getElementById("answerA").innerHTML= answers[0];
    document.getElementById("answerB").value= answers[1];
    document.getElementById("answerB").innerHTML= answers[1];
    document.getElementById("answerC").value= answers[2];
    document.getElementById("answerC").innerHTML= answers[2];
    // 确保选项按钮可见
    document.getElementById("answerA").style.display = 'inline-block';
    document.getElementById("answerB").style.display = 'inline-block';
    document.getElementById("answerC").style.display = 'inline-block';
  } else {
    // 题目全部完成,显示结束按钮
    document.getElementById('endQuiz').style.visibility='visible';
    // 替换提示文字并隐藏选项按钮
    document.getElementById("question").innerHTML= "所有题目已完成!";
    document.getElementById("answerA").style.display = 'none';
    document.getElementById("answerB").style.display = 'none';
    document.getElementById("answerC").style.display = 'none';
  }
}

同时可以优化其他细节:

  1. 去掉adjustScore函数里多余的currentScore+ 0;代码
  2. 修改checkAnswer函数,确保逻辑简洁:
function checkAnswer(answer) {  
  if (answer == randomQuestion.rightAnswer) {
    alert("Congratulations! You got it right!")
    adjustScore(true);
  } else { 
    alert("That's the wrong answer. Wahhhhhh....");
    adjustScore(false);
  }
  // 加载下一题(如果还有的话)
  btnProvideQuestion();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:55:25