使用 vanilla JS 和循环绘制表格

Rob*_*Tan 4 html javascript dom

我正在做一个练习(来自 Beginning Javascript)以更好地理解 DOM 操作。尝试仅使用 JS 以 DRY 方法重新创建下表(教科书解决方案在这里):

<table>
    <tr>
        <td>Car</td>
        <td>Top Speed</td>
        <td>Price</td>
    </tr>
    <tr>
        <td>Chevrolet</td>
        <td>120mph</td>
        <td>$10,000</td>
   </tr>
   <tr>
       <td>Pontiac</td>
       <td>140mph</td>
       <td>$20,000</td>
   </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我尝试了这个,但不确定如何循环变量创建而不抛出错误:

var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from

    var table = document.createElement('table');
    document.body.appendChild(table); // Drew the main table node on the document

    for (var i = 0; i<3; i++) { 
        var tr[i] = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
        table.appendChild(tr[i]); // Append to <table> node

        for (var j = 0; j<3; j++) {

            var tdText = document.createTextNode(array[i][j]); // Extract data from array to a placeholder variable
            tr[i].appendChild(tdText); // Take string from placeholder variable and append it to <tr> node
        }
    }
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 6

正如已经说过的,问题是声明tr[i]变量时的语法错误。

更简洁的方法是使用表 api 方法,例如

var array = [
    ['Car', 'Top Speed', 'Price'],
    ['Chevrolet', '120mph', '$10,000'],
    ['Pontiac', '140pmh', '$20,000']
  ] // Creating a data array which a loop will source from

var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document

array.forEach(function(row) {
  var tr = table.insertRow(); //Create a new row

  row.forEach(function(column) {
    var td = tr.insertCell();
    td.innerText = column; // Take string from placeholder variable and append it to <tr> node
  });
});
Run Code Online (Sandbox Code Playgroud)