Lemonmuncher Lemonmuncher - 1 month ago 6
Javascript Question

Adding array elements to table cells

// Creates a table for my game.
var table = document.createElement("table");
table.border = 1;

// Generates a table with 4 rows and 4 columns
for (var i = 0; i < 4; ++i) {
var row = document.createElement("tr");
table.appendChild(row);

// Creates a cell with the respective number
for (var j = 0; j < 4; ++j) {
var cell = document.createElement("td");
row.appendChild(cell);
cell.appendChild(document.createTextNode(myArray));
};
};

innerDiv.appendChild(table);


I'm making a memorygame in pure Javascript and this is the code I've come up with to generate the gameboard, a table with 4x4 cells. I have an array of 16 randomly generated numbers (1 paif of each number) and want to place one number in each cell, but I can't manage to wrap my head around how to write the code for it.

Answer

Replace

cell.appendChild(document.createTextNode(myArray[k]));

with

cell.appendChild(document.createTextNode(i*4+(j+1)));
Comments