I am trying to make a grid for a game, and I set up the grid, but when I use a for loop to display all of the cells it gives me an error - Uncaught TypeError: Cannot convert undefined or null to object. I think that there is something undefined in the grid array but there shouldn't be. Another theory is that the grid is empty, although it should have 16 cells in it.
let bgCol = '#A6A6A6';
let rows = 4;
let cols = 4;
let grid = [];
let size = 50;
function setup() {
createCanvas(windowWidth, windowHeight);
background(bgCol);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
grid.push(new Cell({x: r * size, y: c * size}, 0));
}
}
}
function draw() {
background(bgCol);
for (let g of grid) {
grid[g].dis();
}
}
class Cell {
constructor(pos, num, col = '#FFFFFF') {
this.pos = pos;
this.num = num;
this.col = col; // White as placeholder until later
}
dis() {
stroke('#000000');
strokeWeight(2);
fill(this.col);
square(this.pos.x, this.pos.y, size, 5);
if (this.num) {
textSize(size - 5);
text(this.num, this.pos.x + 5, this.pos.y + 5);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.11.0/p5.js"></script>
TypeError: grid[g] is undefined. If youprint(g)above the crash, it shows that it's aCellitself, not an index as you assume. So useg.dis(). Better naming helps avoid the misunderstanding:for (const cell of grid) { cell.dis(); }. Also suggest renamingdistodisplay.varbecause it's reassignable and function-scoped, leading to bugs.constprevents reassignment, so you have the stronger guarantee that you won't reassign the value as you do withlet. Generally always useconstexcept for rare cases when you need to reassign, you can then uselet.