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

Vanilla JS中if语句未执行问题求助——立交答题游戏场景

立交识别答题游戏代码无响应问题排查

问题描述

我正在开发一款立交识别答题游戏,逻辑是玩家输入答案后,通过if语句对照预设的answers数组判断答案是否正确,同时结合随机逻辑实现随机出题。编写的核心代码如下:

JavaScript 出题与判分函数

function getRandomImage(){
    var num = Math.floor(Math.random() * 10);
    var img = imageArray[num];
    document.getElementById("question-image").innerHTML = ('<img src="' + img + '"width=450px; height=550px; margin-left: auto; margin-right: auto;">');
    console.log("random image!");
    console.log(answers[num]);
    const textarea = document.getElementById("answer-textarea").value;

    if (document.getElementById("answer-textarea").value == answers[num].toString() && skipCounter > 3){
        console.log(answers[num]);
        score++;
        document.getElementById("score-txt").innerHTML = ("<b>Score: </b>" + "<b>" + score + "</b>");
    }

    else if (document.getElementById("answer-textarea").value != answers[num].toString() && skipCounter > 3){
        console.log(answers[num]);
        score--;
        document.getElementById("score-txt").innerHTML = ("<b>Score: </b>" + "<b>" + score + "</b>");
    }
}

HTML 输入区域

<textarea class="answer-textarea" id="answer-textarea"></textarea>

预设答案数组

answers = new Array();
answers[0] = "Turbine Interchange";
answers[1] = "Complex Roundabout";
answers[2] = "Cloverleaf Interchange";
answers[3] = "High Five";
answers[4] = "Mixing Bowl Interchange";
answers[5] = "Light Horse Interchange";
answers[6] = "T Interchange";
answers[7] = "Trumpet Interchange";
answers[8] = "Vaanplein Junction";
answers[9] = "Ya'an East Road Interchange";

运行时,即使输入与数组匹配的正确答案,代码也无任何响应。添加调试代码和else分支后,始终输出“Did nothing!”。

问题分析

输出“Did nothing!”说明if和else if的条件都未满足,核心原因集中在以下几点:

  • skipCounter > 3条件不成立:判分逻辑被该条件限制,若skipCounter初始值为0或≤3,所有分数增减逻辑都会被跳过,直接进入else分支。这是最可能的触发原因。
  • 输入时机错误:当前逻辑是切换题目(加载新图片)时才读取输入框内容判分,但玩家通常是看到题目后输入答案再提交,导致读取的是上一题输入或未完成的输入,匹配自然失败。
  • 字符串匹配严格性问题:==匹配会严格区分大小写、首尾空格,玩家输入的格式偏差(比如全小写、末尾多空格)都会导致不匹配,但当前逻辑未做容错处理。

修复方案

1. 先移除skipCounter限制,确保判分逻辑正常运行

如果skipCounter不是当前核心需求,先去掉该条件,验证基础判分逻辑:

function getRandomImage(){
    var num = Math.floor(Math.random() * 10);
    var img = imageArray[num];
    // 修正图片样式的语法,放在style属性内
    document.getElementById("question-image").innerHTML = (`<img src="${img}" style="width:450px; height:550px; margin-left: auto; margin-right: auto;">`);
    console.log("random image!");
    console.log(answers[num]);

    // 处理输入的容错:去空格+统一转小写
    const userAnswer = document.getElementById("answer-textarea").value.trim().toLowerCase();
    const correctAnswer = answers[num].toLowerCase();

    if (userAnswer === correctAnswer){
        console.log("正确答案:", answers[num]);
        score++;
    } else {
        console.log("正确答案:", answers[num]);
        score--;
    }
    // 统一更新分数显示,避免重复代码
    document.getElementById("score-txt").innerHTML = `<b>Score: </b><b>${score}</b>`;
    // 清空输入框,方便下一题输入
    document.getElementById("answer-textarea").value = "";
}

2. 分离出题与判分逻辑(更合理的流程)

将加载题目和判分拆分为两个独立函数,符合玩家答题习惯:

// 全局变量存储当前题目的正确答案索引
let currentQuestionIndex = 0;

// 仅负责加载随机题目
function loadRandomQuestion() {
    currentQuestionIndex = Math.floor(Math.random() * 10);
    const img = imageArray[currentQuestionIndex];
    document.getElementById("question-image").innerHTML = `<img src="${img}" style="width:450px; height:550px; margin-left: auto; margin-right: auto;">`;
    console.log("当前正确答案:", answers[currentQuestionIndex]);
    // 清空输入框
    document.getElementById("answer-textarea").value = "";
}

// 单独负责判分
function checkAnswer() {
    const userAnswer = document.getElementById("answer-textarea").value.trim().toLowerCase();
    const correctAnswer = answers[currentQuestionIndex].toLowerCase();

    if (userAnswer === correctAnswer) {
        score++;
        alert("回答正确!");
    } else {
        score--;
        alert(`回答错误,正确答案是:${answers[currentQuestionIndex]}`);
    }
    document.getElementById("score-txt").innerHTML = `<b>Score: </b><b>${score}</b>`;
}

对应的HTML需添加操作按钮:

<textarea class="answer-textarea" id="answer-textarea"></textarea>
<button onclick="checkAnswer()">提交答案</button>
<button onclick="loadRandomQuestion()">下一题</button>

3. 补充变量初始化

确保score等全局变量提前初始化,避免未定义错误:

let score = 0;
let skipCounter = 0; // 根据需求调整初始值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:37:03