【问题标题】:Running into Uncaught TypeError: Cannot read property of undefined遇到未捕获的类型错误:无法读取未定义的属性
【发布时间】:2023-03-15 15:00:02
【问题描述】:

我有一个算法,可以修改一个 10x10 2D 数组,用于 BattleShip 游戏,以随机将船只放置在随机方向。

板子是这样的:

var board= [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 0
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 1
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 2
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 3
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 4
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 5
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 6
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 7
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 8
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]  // 9
];

该算法会将 0 变为 1,并将随机船放置在随机索引和随机方向上。数组是这样的:var array = [5, 4, 3, 3, 2](数字代表长度,例如五个 1、四个 1 等)该算法在大多数情况下运行良好,并且会一直运行到数组为空。

问题是,我偶尔会遇到Uncaught TypeError: Cannot read property of <some integer> undefined,只有在尝试将船置于向上或向下方向时,因为它超出了界限。检查所选方向是否超出范围的 if 语句会发生错误,如下所示:

// check out of bounds for UP direction
if (x - 1 < 0 || array[x - i][y] == undefined) {
  break;
}
// check out of bounds for DOWN direction
if (x + 1 > 9 || array[x + i][y] == undefined) {
  break;
}

我认为错误的发生与尝试执行 array[x - i][y] 和 array[x + i][y] 的负索引有关。我以为我已经通过使用x - 1 &lt; 0 和x + 1 &gt; 9 添加额外的或检查来解决此问题,但我仍然遇到此异常。

【问题讨论】:

  • i是什么,是否也等于1?如果不是,我认为您的边界检查应该是x - i 和x + y。
  • i 是 for 循环的一部分,一直循环到所选船的长度:for (let i = 0; i &lt; randShip; i++)
  • 好的。因此,如果 x 为 1 而y 为 2,那么您的边界检查将无法正常工作。 x - 1 在这种情况下将是 0 但 x - i 将是 -1。
  • 对,那不会等于undefined吗?
  • 是的。然而,当你说array[x - i][y] 和x - i 是undefined 时,你会得到cannot read property of undedined 错误。为什么?因为array[x - i] 的结果是undefined,因此您无法访问[y] 的undefined。如果这有意义?

标签: javascript arrays indexing undefined uncaught-exception


【解决方案1】:

根据 cmets,问题是对 array[x + i] 和 array[x - i] 没有边界检查。因此,对array[x +/- i][y] 的调用会导致cannot read property ... of undefined 错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 2015-01-06
    • 2017-07-26
    • 2019-02-26
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多