ПІДТРИМАЙ УКРАЇНУ ПІДТРИМАТИ АРМІЮ
Uk Uk

2 Ways To Create Table From Array In Javascript

2 Ways To Create Table From Array In Javascript

A quick tutorial for beginners, how to show a (flat) Javascript array in a "nice HTML table". ...

A quick tutorial for beginners, how to show a (flat) Javascript array in a "nice HTML table".

(1) HTML STRING

<!-- (A) EMPTY TABLE -->
<table id="demo"></table>

<script>
// (B) ARRAY OF DATA
var data = ["Alpaca", "Birb", "Cate", "Doge", "Eagle", "Foxe"];

// (C) CREATE TABLE ROWS & CELLS
var table = "<tr>",
 perrow = 2, cells = 0;

data.forEach((value, i) => {
 // (C1) ADD CELL
 table += `<td>${value}</td>`;

 // (C2) CLICK ON CELL TO DO SOMETHING
 // table += `<td onclick="alert($)">${value}</td>`;

 // (C3) BREAK INTO NEXT ROW
 cells++;
 if (cells%perrow==0 && cells!=data.length) { table += "</tr><tr>"; }
});
table += "</tr>";

// (D) ATTACH TO EMPTY TABLE
document.getElementById("demo").innerHTML = table;
</script>
  • (A) All we need for the HTML is an empty <table> .
  • (B) Define your array.
  • (C) Loop through the array, and build an "HTML table string".
    • var table = "<tr>";
    • data.forEach((value, i) => { table += `<td>$</td>`; };
  • (C) Take note of how we split into rows here.
    • 2 cells per row. perrow = 2
    • Use a cells flag to track the current cell.
    • Add a new row for every 2 cells cells%perrow==0
    • But do not add a new row for the last one cells!=data.length
  • (D) Append the "HTML table string" to the empty table.

(2) HTML ELEMENT

<!-- (A) EMPTY TABLE -->
<table id="demo"></table>

<script>
// (B) ARRAY OF DATA
var data = ["Alpaca", "Birb", "Cate", "Doge", "Eagle", "Foxe"];

// (C) CREATE TABLE ROWS & CELLS
var table = document.getElementById("demo"),
 row = table.insertRow(), cell,
 perrow = 2, cells = 0;

data.forEach((value, i) => {
 // (C1) ADD CELL
 cell = row.insertCell();
 cell.innerHTML = value;

 // (C2) CLICK ON CELL TO DO SOMETHING
 cell.onclick = () => alert(i);

 // (C3) BREAK INTO NEXT ROW
 cells++;
 if (cells%perrow==0 && cells!=data.length) { row = table.insertRow(); }
});
  • (C) Alternate method - Get the HTML table. table = document.getElementById("demo"); .
  • (C) Insert new row - row = table.insertRow();
  • (C1) Insert cell - cell = row.insertCell(); cell.innerHTML = value;
Ресурс : dev.to


Scroll to Top