Search code examples
javascriptarraysindexingundefineduncaught-exception

Running into Uncaught TypeError: Cannot read property of undefined


I have an algorithm that will modify a 10x10 2D array for a BattleShip game to randomly place ships down in a random direction.

The board looks like this:

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
];

The algorithm will turn the 0's into 1's and place a random ship at a random index, and at a random direction. The array is like this: var array = [5, 4, 3, 3, 2] (The numbers represent the length e.g. five 1's, four 1's, etc.) The algorithm works good most times and will run until the array is empty.

The problem is, I keep occasionally running into Uncaught TypeError: Cannot read property of <some integer> undefined ONLY when trying to place the ship in either the UP or DOWN direction as it reaches out of bounds. The error occurs for the if statements that check if the direction chosen is out of bounds like so:

// 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;
}

I believe the error is occurring with something to do with the negative index from trying to perform array[x - i][y] and array[x + i][y]. I thought I already fixed this by adding my additional OR check with x - 1 < 0 and x + 1 > 9 but still I am running into this exception.


Solution

  • Per the comments, the problem is there is no bounds checking on array[x + i] and array[x - i]. Because of that, the calls to array[x +/- i][y] result in a cannot read property ... of undefined error.