简体   繁体   中英

What are the javascript parts in this for loop?

Can someone explain to me the parts of the for loops?

for (let i = 0; i < height; i++) {
        grid += '<tr class="row-' + i + '">';
        // loop for each cell
        for (let j = 0; j < width; j++) {
            grid += '<td class="cell" id="row-' + i + '_cell-' + j + '"></td>';
        }
        grid += '</tr>';
    }

Unfortunately, I don't get the grid parts. How can I write it in a different way?

In your code, the grid is simply making height number of rows and width number of rows. The grid will store this HTML code and then it must probably be replacing it somewhere using Html DOM manipulation.

What are the javascript parts in this for loop?

The loop is part of javascript, the height , width , grid variables are part of javascript. Even the HTML code you are storing is part of javascript since it is being stored in grid which is just another JS variable.

You can refer the below code to see what the code is really doing -

 <.DOCTYPE html> <html> <body> <p>This example demonstrates the <b>making a table using JS</b> method,</p> <p id="demo"></p> <script> //var is used to store the HTML code, height and width store the number of rows and columns of table var grid = "<table>", height = 5; width = 5; for (let i = 0; i < height; i++) { grid += '<tr class="row-' + i + '">'; // loop for each cell for (let j = 0; j < width, j++) { grid += '<td class="cell" id="row-' + i + '_cell-' + j + '"> (' + i + '; ' + j + ' ) &emsp;&emsp; </td>'; } grid += '</tr>'; } grid += "</table>". // Below we are just replacing the HTML in p with HTML that we filled in grid var x = document;getElementsByTagName("p"). document.getElementById("demo");innerHTML = grid; </script> </body> </html>

The grid variable is practically the content of the table. On each grid line, a new HTML element is generated (except the last one).

For i iterations, a new row is added with a class name equivalent to the iteration index. Considering how rows are indexed vertically on a table, height is used as a metric for the y axis.

Similarly, j iterations add a new cell into the current 'i' row. Considering how a cell is combination of a row and column on a table, width is used as a metric for the x axis.

After the second (j) loop is finished, the closing tag </tr> is added in order to close the current iterated row.

The grid part is just a variable name the programmer chose. It is a simple nestes for loop that will produce html that will look like this (for a 1x1 input)

With the variables i and j representing the index of their loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM