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

JavaScript检查单词是否在对象数组时出现Uncaught TypeError错误

问题解决:检查单词是否在对象数组中及TypeError错误处理

错误原因分析

  1. TypeError根源:出现Uncaught TypeError: Cannot read properties of undefined (reading 'includes'),大概率是words变量未被正确加载——比如你的主脚本在bigwords.js之前执行,导致words为undefined,无法调用includes方法。
  2. includes方法无效原因:words数组的元素是对象(如{"id":1,"word":"abbreviate"}),而currentGuess是字符串,includes会直接比较元素是否完全相等(对象和字符串永远不相等),所以这个判断逻辑本身就不成立。

解决步骤

1. 确保脚本加载顺序正确

在HTML中,先引入bigwords.js,再引入使用words变量的主脚本,保证words在主脚本执行时已定义:

<script src="bigwords.js"></script>
<script src="你的主脚本文件.js"></script>

2. 替换为正确的单词检查逻辑

因为数组元素是对象,需要遍历数组检查每个对象的word属性是否与currentGuess匹配,推荐使用some()方法(高效,找到匹配项就停止遍历):

// 先做基础校验,避免变量未定义导致后续错误
if (!words || typeof currentGuess !== 'string') {
  return;
}

// 检查是否存在匹配的单词(忽略大小写,如需严格匹配可去掉toLowerCase())
const isWordValid = words.some(wordObj => wordObj.word.toLowerCase() === currentGuess.toLowerCase());

if (!isWordValid) {
  document.getElementById('tip').innerHTML = "Word not in dictionary";
  console.log('word not contained in dictionary');
  return;
}

也可以使用find()方法实现,逻辑类似:

const matchedWord = words.find(wordObj => wordObj.word === currentGuess);
if (!matchedWord) {
  document.getElementById('tip').innerHTML = "Word not in dictionary";
  console.log('word not contained in dictionary');
  return;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:23:19