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

JS开发吃豆人游戏出现cannot read properties of undefined报错如何解决

错误原因

你遇到的三个报错都是代码逻辑错误导致访问了不存在的DOM元素引发的,核心错误有两处:

  • 方向随机逻辑索引越界
    你定义的allDirections数组长度为4,合法索引范围是0-3,但初始随机值的代码写为let random = Math.floor(Math.random() * 4) + 1,生成的随机数范围是1-4,当取到4时allDirections[4]为undefined,后续计算的位置下标非法,访问squares[非法下标]得到的就是undefined,调用它的classList相关方法自然会报错。
  • 幽灵位置更新逻辑写错
    你写的 squares[ghost.position] += direction是错误逻辑,这行代码会直接把squares数组中对应下标的DOM元素修改为数字,而不是更新幽灵的位置属性。正确写法应该是更新幽灵实例的position属性。

修复方案

仅需要修改moveGhost函数即可解决报错,修改后代码如下:

function moveGhost(ghost) {
  const allDirections = [-1, +1, -width, +width];
  // 修正随机索引范围,确保在合法区间内
  let direction = allDirections[Math.floor(Math.random() * allDirections.length)];

  setInterval(() => {
    // 增加下标越界判断,避免访问不存在的元素
    const nextPosition = ghost.position + direction;
    if (nextPosition >=0 && nextPosition < squares.length && !squares[nextPosition].classList.contains('wall')) {
      // 从旧位置移除幽灵样式
      squares[ghost.position].classList.remove(ghost.name)
      squares[ghost.position].classList.remove('ghost')
      // 修正:更新幽灵实例的位置属性
      ghost.position = nextPosition;
      // 给新位置添加幽灵样式
      squares[ghost.position].classList.add(ghost.name);
      squares[ghost.position].classList.add('ghost');
    } else {
      direction = allDirections[Math.floor(Math.random() * allDirections.length)]
    }
  }, 2500)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:27:05