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

JavaScript循环匹配元素时if else未按预期运行,逻辑问题排查求助

问题原因

你代码的核心问题是混淆了**字符串includes()和数组includes()**的逻辑:

  • 当前你定义的wordsIncorrect是字符串类型,调用字符串的includes()时,只要传入的内容是该字符串的子串就会返回true。你要匹配的单词cat是wordsIncorrect中cattle的子串,所以wordsIncorrect.includes('cat')会判定为真,直接进入push(false)的分支,不会触发else逻辑。
  • 你实际需要的是匹配完全相等的独立单词,需要用到数组的includes()方法,只有数组中存在和当前遍历项完全相等的元素时才返回真。
修复方案

先把错误单词的字符串转为数组,再用数组的includes()做匹配即可,修复后代码如下:

const wordPerformance = []
const wordsReviewed   = "candy, cattle, cat, call, cheat";
// 将错误单词字符串切割为数组,用于后续完整单词匹配
const wordsIncorrect  = "candy, cattle, call, cheat".split(/,\s?/);

wordsReviewed.split(/,\s?/).forEach((word) => {
  if (wordsIncorrect.includes(word)) {
    wordPerformance.push(false);
  } else {
    console.log(word) // 此时会正常输出 'cat'
    wordPerformance.push(true);
  }
});

console.log(wordPerformance); // 输出预期结果:[false, false, true, false, false]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:24:03