从2D JavaScript数组生成HTML表

Generate HTML table from 2D JavaScript array

本文关键字:HTML 数组 2D JavaScript      更新时间:2023-09-26

在JavaScript中,是否可以从2D数组生成HTML表?编写HTML表的语法往往非常冗长,所以我想从2D JavaScript数组生成一个HTML表,如下所示:

[
  ["row 1, cell 1", "row 1, cell 2"], 
  ["row 2, cell 1", "row 2, cell 2"]
]

将成为:

<table border="1">
  <tr>
    <td>row 1, cell 1</td>
    <td>row 1, cell 2</td>
  </tr>
  <tr>
    <td>row 2, cell 1</td>
    <td>row 2, cell 2</td>
  </tr>
</table>

所以我试图写一个JavaScript函数,将返回一个表从一个2D JavaScript数组,如下所示:

function getTable(array){
  // take a 2D JavaScript string array as input, and return an HTML table.
}

这个函数将使用dom而不是字符串连接。

function createTable(tableData) {
  var table = document.createElement('table');
  var tableBody = document.createElement('tbody');
  tableData.forEach(function(rowData) {
    var row = document.createElement('tr');
    rowData.forEach(function(cellData) {
      var cell = document.createElement('td');
      cell.appendChild(document.createTextNode(cellData));
      row.appendChild(cell);
    });
    tableBody.appendChild(row);
  });
  table.appendChild(tableBody);
  document.body.appendChild(table);
}
createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);

使用双for循环非常容易。

function makeTableHTML(myArray) {
    var result = "<table border=1>";
    for(var i=0; i<myArray.length; i++) {
        result += "<tr>";
        for(var j=0; j<myArray[i].length; j++){
            result += "<td>"+myArray[i][j]+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";
    return result;
}

这是一个使用模板文字的版本。它maps在数据上创建从模板字面值构建的新的字符串数组,然后用insertAdjacentHTML:

将它们添加到文档中。

let data = [
  ['Title', 'Artist', 'Duration', 'Created'],
  ['hello', 'me', '2', '2019'],
  ['ola', 'me', '3', '2018'],
  ['Bob', 'them', '4.3', '2006']
];
function getCells(data, type) {
  return data.map(cell => `<${type}>${cell}</${type}>`).join('');
}
function createBody(data) {
  return data.map(row => `<tr>${getCells(row, 'td')}</tr>`).join('');
}
function createTable(data) {
  // Destructure the headings (first row) from
  // all the rows
  const [headings, ...rows] = data;
  // Return some HTML that uses `getCells` to create
  // some headings, but also to create the rows
  // in the tbody.
  return `
    <table>
      <thead>${getCells(headings, 'th')}</thead>
      <tbody>${createBody(rows)}</tbody>
    </table>
  `;
}
// Bang it altogether
document.body.insertAdjacentHTML('beforeend', createTable(data));
table { border-collapse: collapse; }
tr { border: 1px solid #dfdfdf; }
th, td { padding: 2px 5px 2px 5px;}

另一个没有innerhtml的版本。

function makeTable(array) {
    var table = document.createElement('table');
    for (var i = 0; i < array.length; i++) {
        var row = document.createElement('tr');
        for (var j = 0; j < array[i].length; j++) {
            var cell = document.createElement('td');
            cell.textContent = array[i][j];
            row.appendChild(cell);
        }
        table.appendChild(row);
    }
    return table;
}

一个es6版本的Daniel Williams的回答:

  function get_table(data) {
    let result = ['<table border=1>'];
    for(let row of data) {
        result.push('<tr>');
        for(let cell of row){
            result.push(`<td>${cell}</td>`);
        }
        result.push('</tr>');
    }
    result.push('</table>');
    return result.join(''n');
  }

一行使用es6 reduce

function makeTableHTML(ar) {
  return `<table>${ar.reduce((c, o) => c += `<tr>${o.reduce((c, d) => (c += `<td>${d}</td>`), '')}</tr>`, '')}</table>`
}

查看从数组创建表的演示。

function createTable(tableData) {
  var table = document.createElement('table');
  var row = {};
  var cell = {};
  tableData.forEach(function(rowData) {
    row = table.insertRow(-1); // [-1] for last position in Safari
    rowData.forEach(function(cellData) {
      cell = row.insertCell();
      cell.textContent = cellData;
    });
  });
  document.body.appendChild(table);
}

你可以这样使用

var tableData = [["r1c1", "r1c2"], ["r2c1", "r2c2"], ["r3c1", "r3c2"]];
createTable(tableData);

基于接受的解决方案:

function createTable (tableData) {
  const table = document.createElement('table').appendChild(
    tableData.reduce((tbody, rowData) => {
      tbody.appendChild(
        rowData.reduce((tr, cellData) => {
          tr.appendChild(
            document
              .createElement('td')
              .appendChild(document.createTextNode(cellData))
          )
          return tr
        }, document.createElement('tr'))
      )
      return tbody
    }, document.createElement('tbody'))
  )
  document.body.appendChild(table)
}
createTable([
  ['row 1, cell 1', 'row 1, cell 2'],
  ['row 2, cell 1', 'row 2, cell 2']
])

通过简单的更改,可以将表作为HTML元素返回

生成表格并支持HTML作为输入

灵感来自@spiny-normanhttps://stackoverflow.com/a/15164796/2326672

和@borndhttps://stackoverflow.com/a/6234804/2326672

function escapeHtml(unsafe) {
    return String(unsafe)
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }
function makeTableHTML(myArray) {
    var result = "<table border=1>";
    for(var i=0; i<myArray.length; i++) {
        result += "<tr>";
        for(var j=0; j<myArray[i].length; j++){
            k = escapeHtml((myArray[i][j]));
            result += "<td>"+k+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";
    return result;
}

在这里用JSFIDDLE测试-直接从Microsoft Excel粘贴得到表

let data = [
  ['Title', 'Artist', 'Duration', 'Created'],
  ['hello', 'me', '2', '2019'],
  ['ola', 'me', '3', '2018'],
  ['Bob', 'them', '4.3', '2006']
];
function getCell (cell, type='td') {
        return `<${type}>${cell}</${type}>`
}
function getCells(cells, type='td') {
        return cells.map(cell => getCell(cell, type)).join('');
}
function getRow(row) {
        return `<tr> ${getCell(row[0], 'th')} ${getCells(row.slice(1))} </tr>`
} 
          
function createTable(data) {
  const [headings, ...rows] = data;
      
    return `
          <table>
            <thead>${getCells(headings, 'th')}</thead>
            <tbody>${rows.map(getRow).join('')}</tbody>
          </table>
    `;
}
document.body.insertAdjacentHTML('beforeend', createTable(data));
table { border-collapse: collapse; }
tr { border: 1px solid #dfdfdf; }
th, td { padding: 4px;}

这是@Andy的答案的精确副本,稍加修改,使每行的第一个单元格将是th

没有新行的纯函数表(只是为了好玩)

const pureFunctionalTable = data => 
    [document.createElement('table')].filter(table => !table.appendChild(
        data.reduce((tbody, row) =>
            !tbody.appendChild(row.reduce((tr, cell) =>
                !tr.appendChild(document.createElement('td'))
                   .appendChild(document.createTextNode(cell)) || tr
                , document.createElement('tr'))
            ) || tbody, document.createElement('tbody'))) || table)[0];

使用

document.body.appendChild(pureFunctionalTable([
    ['row 1, cell 1', 'row 1, cell 2'],
    ['row 2, cell 1', 'row 2, cell 2']
]));

我知道这是一个古老的问题,但对于那些像我一样细读网络的人来说,这里有另一个解决方案:

在逗号上使用replace()并创建一组字符以确定行结束。我只是将--添加到内部数组的末尾。这样你就不需要运行for函数了。

这是一个JSFiddle: https://jsfiddle.net/0rpb22pt/2/

首先,你必须在你的HTML中得到一个表格,并给它一个id:

<table id="thisTable"><tr><td>Click me</td></tr></table>

这是你为这个方法编辑的数组:

thisArray=[["row 1, cell 1__", "row 2, cell 2--"], ["row 2, cell 1__", "row 2, cell 2"]];

注意在每个数组末尾添加的--

因为在数组的内也有逗号,所以必须以某种方式区分它们,这样就不会弄乱您的表-在单元格之后添加__(除了一行中的最后一个)可以工作。如果单元格中没有逗号,则不需要执行此步骤。

现在是你的函数:

function tryit(){
  document
    .getElementById("thisTable")
    .innerHTML="<tr><td>"+String(thisArray)
    .replace(/--,/g,"</td></tr><tr><td>")
    .replace(/__,/g,"</td><td>");
}

它是这样工作的:

  1. 调用您的表并设置innerHTMLdocument.getElementById("thisTable").innerHTML
  2. 首先添加HTML标签来开始一行和数据。"<tr><td>"
  3. 增加thisArray作为String()+String(thisArray)
  4. 将每个在新行之前结束的--替换为数据和行的关闭和打开。.replace(/--,/g,"</td></tr><tr><td>")
  5. 其他逗号表示行中单独的数据。因此,替换数据的结束和开始的所有逗号。在这种情况下,并非所有逗号都在行之间,因为单元格有逗号,所以我们必须用__: .replace(/__,/g,"</td><td>")区分它们。通常你只需要输入.replace(/,/g,"</td><td>")

只要您不介意在数组中添加一些多余的字符,它将占用更少的代码并且易于实现。

这是一个带有"table header"实现的holder答案

function createTable(tableData) {
  var table = document.createElement('table');
  var header = document.createElement("tr");
  // get first row to be header
  var headers = tableData[0];
  // create table header
  headers.forEach(function(rowHeader){
    var th = document.createElement("th");
    th.appendChild(document.createTextNode(rowHeader));
    header.appendChild(th);
  });      
  console.log(headers);
  // insert table header 
  table.append(header);
  var row = {};
  var cell = {};
  // remove first how - header
  tableData.shift();
  tableData.forEach(function(rowData, index) {
    row = table.insertRow();
    console.log("indice: " + index);
    rowData.forEach(function(cellData) {
      cell = row.insertCell();
            cell.textContent = cellData;
    });
  });
  document.body.appendChild(table);
}

不知道([["行1单元1"、"行1单元2"],["行2单元1"、"行2单元2"],["行3单元1号"、"行3单元2"]]);

下面是一个如何从矩阵m x n中生成和读取数据的示例…在JavaScript中

let createMatrix = (m, n) => {
      let [row, column] = [[], []],
          rowColumn = m * n
      for (let i = 1; i <= rowColumn; i++) {
        column.push(i)
        if (i % n === 0) {
          row.push(column)
          column = []
        }
      }
      return row
    }
let setColorForEachElement = (matrix, colors) => {
  let row = matrix.map(row => {
    let column = row.map((column, key) => {
      return { number: column, color: colors[key] }
    })
    return column
  })
  return row
} 
const colors = ['red', 'green', 'blue', 'purple', 'brown', 'yellow', 'orange', 'grey']
const matrix = createMatrix(6, 8)
const colorApi = setColorForEachElement(matrix, colors)
let table ='<table>'
colorApi.forEach(row => {
  table+= '<tr>'
    row.forEach(column =>  table += `<td style='background: ${column.color};'>${column.number}<td>` )
  table+='</tr>'
})
table+= '</table>'
document.write(table);

以ar为数组的10美分:

'<table><tr>'+ar.map(e=>'<td>'+e.join('</td><td>')+'</td>').join('</tr><tr>')+'</tr></table>'

对于不想使用DOM的用户

function test_makeTableHTML() {
  var array = [
    ['num', 'date', 'text'],
    [1, new Date(), 'foo'],
    [2, new Date(), 'bar'],
  ]
  var htmltable = makeTableHTML_(array);
  console.log(htmltable);
}
/**
 * creates HTML table code
 * ⚠️ not a DOM-element!
 * from 2d array with a header
 * 
 */
function makeTableHTML_(array) {
    var result = "<table border='1' style='border-collapse:collapse'><tr>";
    var header = array[0];
    for (var i = 0; i < header.length; i++) {
      result += "<th>"+header[i]+"</th>";
    }
    result += "</tr>";
    var val;
    for(var i = 1; i<array.length; i++) {
        result += "<tr>";
        for(var j=0; j<array[i].length; j++){
          val = array[i][j];
          if (val instanceof Date) {
            val = formatDate_(val);
          }
            result += "<td>"+val+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";
    return result;
}
/**
 * converts JS date
 * to human's date
 * 
 */
// https://stackoverflow.com/a/34015511/5372400
function formatDate_(date) {
  var options = { 
    weekday: 'long', 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric' };
  return date.toLocaleDateString("en-US", options);
}

测试https://html5-editor.net

React JSX解决方案:

let array2d = [
  ["row 1, cell 1", "row 1, cell 2"], 
  ["row 2, cell 1", "row 2, cell 2"]
];

像这样使用。map:

<table border="1">
{
array2d.map((array) => 
<tr>
<td>{array[0]}</td>
<td>{array[1]}</td>
</tr>
)}
</table>