I am learning how to incorporate JavaScript into HTML and am trying to build a very simple web game based off a class project. (This is a sidebar, I successfully completed the project itself.)
I need two specific images to randomly populate the entire table. My code successfully creates the array of appropriate length and translates that correctly to the HTML, but the image sources don’t seem to populate correctly. One image of each always shows up so I am confident my source paths are correct, and one of the images is always in the lower right hand corner, but the rest of the field is blank. When examining DevTools the array is there with appropriate img
attributes but there is no source, except obviously on the img
‘s that have a visible image.
class Field {
static generateField(h, w, pct = .2) {
let board = [];
let tempArray = [];
while (board.length < h) {
while (tempArray.length < w) {
const random = Math.random();
if (random < pct) {
tempArray.push(imageB);
} else {
tempArray.push(imageA);
}
}
board.push(tempArray);
}
for (let a = 0; a < h; a++) {
let row = document.createElement("tr");
for (let b = 0; b < w; b++) {
let cell = document.createElement("td");
let img = document.createElement("img");
img = board[a][b];
img.style.width = "100%";
img.style.height = "100%";
cell.appendChild(img);
row.appendChild(cell);
}
tblBody[0].appendChild(row);
}
}
}
The tblBody
is defined outside the class
. Originally my code was nested for
loops and gave the exact same result.
Where am I going wrong?