Suppose we have some empty table:
<table id="table"></table>
Suppose we also have some two-dimensional array, for example, this:
let arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
Let's make an HTML table based on this array,
filled with the elements of this array. That is,
we will get a table with three rows, each row will
have 4
cells.
Solve the problem with two nested
for-of
loops:
let arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
let table = document.querySelector('#table');
for (let subArr of arr) {
let tr = document.createElement('tr');
for (let elem of subArr) {
let td = document.createElement('td');
td.textContent = elem;
tr.appendChild(td);
}
table.appendChild(tr);
}
As you can see, our solution turned out to be universal and does not depend on the number of subarrays and the number of elements in each subarray. The only condition is that the subarrays have the same number of elements.
Given an array:
let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]];
Without looking into the theoretical part of the
lesson, output the elements of the given array as
an HTML table table
.
Modify the previous task so that the table doesn't contain elements, but the squares of these elements.