There is a two-dimensional array, or rather a function that creates it:

function createMatrix(width, height) { var matrix = []; var coll = []; for (var i = 0; i < width; i++) { matrix[i] = coll; for (var j = 0; j < height; j++) { var div = document.createElement('div'); div.className = 'cell'; matrix[i][j] = div; } } return matrix; } 

And there is div.field , how to display a grid of the width at height consisting of div.field filled with array elements (in this case, the div is you). For example:

 var f = createMatrix(20, 20); 

It is expected to receive a grid with the size of 20 rows, 20 columns with cells filled with divas.

  • 2
    and what is the question? By the way, the function does not work correctly :) - Grundy
  • one
    Anyway, the above function does not work correctly. - Qwertiy
  • And nothing, that your function replicates the array coll several times in the array matrix? In fact, you get a meaningless structure, because each matrix dimension contains the same element. Oh yeah, the most important thing is forgotten - what do you mean by "draw array"? - Alex Krass
  • one
    so the question is what, if in Russian words if you describe? - Jean-Claude
  • one
    do not put a space between @ and nickname, otherwise the alert does not come. - Grundy

1 answer 1

First, your function will not work for one simple reason - you are not creating a new one in the matrix array and, accordingly, each cell will contain the same coll array, that is, matrix[0] == matrix[1] == matrix[3] . And in the coll array, elements that you can insert only once per page. Even if you cycle through the height of the matrix, you will be stuck in the same div that is already on the page.

Therefore, you need to redo the function, and inserting into the DOM is a standard operation, which can be read about in a tutorial or tutorial, nothing special.

 function createMatrix(width, height) { var matrix = []; for (var i = 0; i < height; i++) { matrix[i] = []; for (var j = 0; j < width; j++) { var div = document.createElement('div'); div.className = 'cell'; matrix[i][j] = div; } } return matrix; } document.getElementById("b").onclick = function(){ var w = parseInt(document.getElementById("w").value); var h = parseInt(document.getElementById("h").value); var m = createMatrix(w,h); var d = document.getElementsByClassName("field")[0]; for(var i=0; i<m.length; i++){ var row = m[i] for(var j=0; j<row.length; j++){ d.appendChild(row[j]); } d.appendChild(document.createElement('div')); //для разделения строк } } 
 .cell{ display: inline-block; width: 50px; height: 50px; border: 1px solid black; } 
 Введите ширину: <input id="w" type="text"> <br> Введите высоту: <input id="h" type="text"> <br> <button id="b">отрисовать</button> <br> <div class="field"> </div>