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

如何遍历两个数组并对比元素?实现听写文本校验功能遇阻

听写文本对比功能的正确实现

你的两段代码都存在逻辑错误,导致无法正常实现对比功能,具体问题和修复方案如下:

原代码的核心问题

  • 嵌套循环逻辑错误:你用了两层for循环,让每个正确单词和所有输入单词逐一对比,这会生成大量重复内容,完全不符合"按顺序逐个单词对比"的听写需求。
  • 状态更新混乱:第二种方案里多次调用setAnswer,React状态更新是异步的,多次调用会导致状态叠加错误;第一种方案每次提交都会把新结果追加到旧的answer数组里,没有重置,导致历史内容残留。
  • 未处理边界情况:没考虑用户输入单词数和正确文本单词数不一致的情况(比如多输、少输单词)。

正确实现代码

import { useState } from 'react';

export default function Dictation() {
  const [value, setValue] = useState("");
  const [correctText, setCorrectText] = useState("Every day I work hard to achieve my goals");
  const [answer, setAnswer] = useState<{ word: string; isCorrect: boolean }[]>([]);

  const compare = () => {
    const correctWords = correctText.split(" ");
    const inputWords = value.split(" ");
    const result: { word: string; isCorrect: boolean }[] = [];

    // 遍历正确单词数组,逐个对比输入单词
    for (let i = 0; i < correctWords.length; i++) {
      const correctWord = correctWords[i];
      const inputWord = inputWords[i];

      if (inputWord && inputWord === correctWord) {
        result.push({ word: correctWord, isCorrect: true });
      } else {
        // 输入为空或错误,显示正确单词并标记错误
        result.push({ word: correctWord, isCorrect: false });
      }
    }

    // 处理用户输入多余的单词(正确文本没有的部分)
    if (inputWords.length > correctWords.length) {
      for (let i = correctWords.length; i < inputWords.length; i++) {
        result.push({ word: inputWords[i], isCorrect: false });
      }
    }

    setAnswer(result);
  };

  return (
    <div style={{ padding: '20px' }}>
      <input
        value={value}
        onChange={(e) => setValue(e.target.value)}
        style={{ padding: '8px', width: '400px' }}
        placeholder="输入听写内容"
      />
      <button onClick={compare} style={{ marginLeft: '10px', padding: '8px 16px' }}>
        提交对比
      </button>
      <div style={{ marginTop: '20px' }}>
        {answer.map((item, index) => (
          <span
            key={index}
            style={{
              marginRight: '8px',
              color: item.isCorrect ? 'green' : 'red',
              textDecoration: item.isCorrect ? 'none' : 'line-through'
            }}
          >
            {item.word}
          </span>
        ))}
      </div>
    </div>
  );
}

代码说明

  1. 状态结构优化:把answer改成包含单词和正确性标记的对象数组,方便后续渲染时区分样式。
  2. 对比逻辑修正:按索引逐个对比正确单词和输入单词,确保顺序一致,符合听写的核心需求。
  3. 边界处理:额外处理输入单词数多于正确单词数的情况,把多余的单词标记为错误。
  4. 状态重置:每次对比都会生成全新的结果数组,替换旧的answer状态,避免历史内容残留。
  5. 视觉反馈:用颜色和删除线区分正确/错误的单词,符合听写功能的交互逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:33:17