【发布时间】: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 < 0 和x + 1 > 9 添加额外的或检查来解决此问题,但我仍然遇到此异常。
【问题讨论】:
-
i是什么,是否也等于1?如果不是,我认为您的边界检查应该是x - i和x + y。 -
i是 for 循环的一部分,一直循环到所选船的长度:for (let i = 0; i < 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