As a novice coder, I'm seeking assistance with a basic issue that has me stumped despite my attempts to find a solution. My grid consists of arrays nested within an array named 'cells', filled with 1s and 0s representing live and dead cells. My goal is to search the eight neighboring positions for each cell on the grid using nested for loops:
//iterate through the entire board
for (y = 0; y < cells.length; y++) {
for (x = 0; x < cells[0].length; x++) {
let liveNeighbours = 0;
let deadNeighbours = 0;
//iterate over neighbors in a 9-cell grid, excluding the current cell
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('Analyzing cell at position: ' + x + ', ' + y);
console.log('Number of live neighbours: ' + liveNeighbours);
console.log('Number of dead neighbours: ' + deadNeighbours);
}
}
}
}
Although this method seems straightforward, it sometimes results in attempts to access undefined array indexes (such as cells[-1][-1]). I've attempted to address this by including a typeof check, but I'm still encountering the error:
TypeError: Cannot read property '-1' of undefined
The code fails to execute the typeof operation because the value is undefined, despite my intention to evaluate it. What am I missing here?