返回

在 CardSimulate 中,重构原生JavaScript绘制表格的代码

前端

重构代码是为了让它变得更加清晰、易于维护和扩展,从而提高代码的可读性和可维护性。

以下是重构后的代码:

function createTable(data) {
  const table = document.createElement('table');
  const thead = document.createElement('thead');
  const tbody = document.createElement('tbody');

  // Create the table header
  const headerRow = document.createElement('tr');
  for (const key in data[0]) {
    const th = document.createElement('th');
    th.innerText = key;
    headerRow.appendChild(th);
  }
  thead.appendChild(headerRow);

  // Create the table body
  for (const row of data) {
    const tr = document.createElement('tr');
    for (const value of Object.values(row)) {
      const td = document.createElement('td');
      td.innerText = value;
      tr.appendChild(td);
    }
    tbody.appendChild(tr);
  }

  // Append the header and body to the table
  table.appendChild(thead);
  table.appendChild(tbody);

  return table;
}

下面是使用这个函数的示例:

const data = [
  { name: 'John', age: 30 },
  { name: 'Mary', age: 25 },
  { name: 'Bob', age: 40 }
];

const table = createTable(data);

document.body.appendChild(table);

这将创建一个表格,其中包含三行和两列,第一列是名称,第二列是年龄。

重构后的代码比原始代码更清晰、更易于维护和扩展。它还更易于阅读和理解。