SeeBread
SeeBread

Reputation: 1

Searching an array: TypeError: Cannot read property of undefined

Beginner coder here, so forgive me, I've searched but can't find anything to help me with this basic issue.

I have grid in the form of arrays within an array called 'cells', populated with 1s and 0s, representing living and dead cells. For each place on the grid I want to search the 8 places that surround it. I execute this with for loops:

  
    
    //iterate through the whole board
    
    for (y = 0; y < cells.length; y++) {
      for (x = 0; x < cells[0].length; x++) {
        
        let liveNeighbours = 0;
        let deadNeighbours = 0;
        
        //iterate through neighbours in 9 cell grid, ignore the cell itself
        for (yy = y - 1; yy <= y + 1; yy++) {
          for (xx = x - 1; xx <= x + 1; xx++) {
              if (yy !== y || xx !== x) {
                
                if (typeof(cells[yy][xx]) !== 'undefined') {
                  if (cells[yy][xx] === 1) {
                    liveNeighbours++;
                  } else if (cells[yy][xx] === 0) {
                    deadNeighbours++;
                  }
                }

            }
          }
        }
        
        console.log('Looking at cell ' + x + ', ' + y);
        console.log('Live neighbours ' + liveNeighbours);
        console.log('Dead neighbours ' + deadNeighbours);        
        
        
      }
    }
    
  }
}

This seems like the simplest method, although obviously it means that the search will occassionally be looking at undefined array indexes (cells[-1][-1]). I've tried to get around this by implementing a typeof check but I still receive the error:

TypeError: Cannot read property '-1' of undefined

It refuses to check the typeof because it is undefined, even though that's exactly what I want to know. What am I doing wrong here?

Upvotes: 0

Views: 95

Answers (2)

user4945014
user4945014

Reputation:

Maybe a better way to do it:

cells[yy]?.[xx]

Using the optional chaining operator. Will return undefined if either cells[yy] or cells[yy][xx] is undefined.

That way you don't need that if wrapper at all because undefined !== 1 and undefined !== 0.

Old code:

if (typeof(cells[yy][xx]) !== 'undefined') {
    if (cells[yy][xx] === 1) {
        liveNeighbours++;
    } else if (cells[yy][xx] === 0) {
        deadNeighbours++;
    }
}

New code:

if (cells[yy]?.[xx] === 1) {
    liveNeighbours++;
} else if (cells[yy]?.[xx] === 0) {
    deadNeighbours++;
}

Edit: CanIUse Optional Chaining Operator? (Yes, except for IE)

Upvotes: 1

Barmar
Barmar

Reputation: 781058

You're pretty close. The problem is that typeof(cells[yy][xx]) !== "undefined" will not work when yy is out of range, because it will try to access a subscript of undefined.

Change that to

if (typeof cells[yy] !== "undefined" && typeof cells[yy][xx] !== "undefined")

Upvotes: 0

Related Questions