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

如何实现数组中日语词汇问题与对应罗马音答案的关联验证?

如何实现数组中日语词汇问题与对应罗马音答案的关联验证?

嘿,我来帮你排查下这个问题!你把日语词汇和对应罗马音用同索引数组关联的思路完全没问题,现在验证逻辑里有几个小细节没处理好,导致正确答案不被识别,我们一步步来修正:

1. 先确认当前题目的索引是否正确传递

你写的checkIfRightAnswer(index)函数需要接收当前题目的索引,但如果调用这个函数时没传对索引(比如按钮点击事件里没传当前题目序号),index会是undefined,那correctAnswer[index]也会是undefined,自然永远匹配不上用户输入。

解决方法:我们可以定义一个全局变量currentQuestionIndex来跟踪当前显示的是第几题,不用再手动传索引,更不容易出错。

2. 修正验证函数里的条件判断

你的else if (!correctAnswer[index] && !ended)条件有问题——你的correctAnswer数组里每个元素都有值,!correctAnswer[index]永远不会成立,错误提示其实根本没走这个分支。直接改成else更合理:只要输入不等于正确答案,就提示错误。

3. 实时获取用户输入的内容

你在函数外定义了var userInput = document.getElementById("user-input"),但userInput.value是页面加载时的初始值(空),用户后续输入的内容不会自动更新到这个变量里。所以要在验证函数内部实时获取输入值,还可以加个trim()去掉前后空格,避免用户不小心输入空格导致匹配失败。


修正后的完整代码示例

JavaScript部分:

// 全局变量跟踪当前题目索引
let currentQuestionIndex = 0;

// 题目和答案数组
const questionsList = [
  "体調", "体温", "病気", "風邪", "食欲", "検査", "異常", "手術", "回復", "薬局", "傷", "火傷", "胃", "肩", "胸", "腰", "膝", "心臓",
];
const correctAnswer = [
  "たいちょう", "たいおん", "びょうき", "かぜ", "しょくよく", "けんさ", "いじょう", "しゅじゅつ", "かいふく", "やっきょく", "きず", "やけど", "い", "かた", "むね", "こし", "ひざ", "しんぞう",
];

// 显示当前题目函数
function showQuestion() {
  // 假设你有个显示题目的元素id是question-display
  const questionEl = document.getElementById("question-display");
  questionEl.textContent = questionsList[currentQuestionIndex];
  
  // 每次切换题目时清空输入框和反馈
  document.getElementById("user-input").value = "";
  document.getElementById("feedback").textContent = "";
}

// 验证答案函数
function checkIfRightAnswer() {
  // 实时获取用户输入(去掉前后空格)
  const userInputValue = document.getElementById("user-input").value.trim();
  // 获取当前题目的正确答案
  const currentCorrect = correctAnswer[currentQuestionIndex];
  const feedbackEl = document.getElementById("feedback");

  if (userInputValue === currentCorrect) {
    feedbackEl.style.color = "seagreen";
    feedbackEl.textContent = "C'est juste!";
    
    // 判断是否是最后一题
    if (currentQuestionIndex < questionsList.length - 1) {
      // 延迟1秒切换下一题,让用户看到正确提示
      setTimeout(() => {
        currentQuestionIndex++;
        showQuestion();
      }, 1000);
    } else {
      // 所有题目完成
      feedbackEl.textContent = "Quiz terminé! Bravo!";
    }
  } else {
    feedbackEl.style.color = "red";
    feedbackEl.textContent = "Mauvaise réponse, réessayez encore une fois!";
  }
}

// 页面加载完成后显示第一题
window.onload = showQuestion;

HTML部分(配合JS的结构):

<div id="question-display"></div>
<input type="text" id="user-input" placeholder="Entrez la réponse ici">
<button onclick="checkIfRightAnswer()">Valider</button>
<div id="feedback"></div>

这样修改后,应该就能正常识别正确答案,错误提示也能正常工作啦!核心就是确保当前题目索引正确、实时获取输入值,还有条件判断逻辑正确。

备注:内容来源于stack exchange,提问作者Ham

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 08:04:34