簡體   English   中英

從二維 JavaScript 數組生成 HTML 表

[英]Generate HTML table from 2D JavaScript array

在JavaScript中,是否可以從二維數組生成HTML表? 寫HTML表的語法往往很冗長,所以我想從一個二維的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 function 將從二維 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;
}

另一個沒有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;
}

Daniel Williams 回答的 es6 版本:

  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');
  }

請參閱小提琴演示以從數組創建表

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 元素返回。

單行使用 es6 reduce

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

生成表格並支持 HTML 作為輸入。

靈感來自@spiny-norman https://stackoverflow.com/a/15164796/2326672

還有@bornd https://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 粘貼以獲取表格

我知道這是一個老問題,但對於像我這樣瀏覽網頁的人來說,這是另一個解決方案:

在逗號上使用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. 調用您的表並開始設置innerHTML document.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>")

只要您不介意在數組中添加一些雜散字符,它占用的代碼就會少得多,而且實現起來也很簡單。

如果你不介意 jQuery,我正在使用這個

<table id="metaConfigTable">
    <caption>This is your target table</caption>
    <tr>
        <th>Key</th>
        <th>Value</th>
    </tr>
</table>

<script>

    function tabelajzing(a){ 
    // takes (key, value) pairs from and array and returns
    // corresponding html, i.e. [ [1,2], [3,4], [5,6] ] 
      return [
        "<tr>\n<th>",
        a.map(function (e, i) {
          return e.join("</th>\n<td>")
        }).join("</td></tr>\n<tr>\n<th>"),
        "</td>\n</tr>\n"
      ].join("")
    }

  $('#metaConfigTable').find("tr").after(
      tabelajzing( [ [1,2],[3,4],[5,6] ])
  );
</script>

這是帶有“表頭”實現的 holmberd 答案

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);
}

createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"], ["row 3, cell 1", "row 3, 單元格 2"]]);

這是使用模板文字的版本。 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) { const [headings, ...rows] = data; return ` <table> <thead>${getCells(headings, 'th')}</thead> <tbody>${createBody(rows)}</tbody> </table> `; } document.body.insertAdjacentHTML('beforeend', createTable(data));
 table { border-collapse: collapse; } tr { border: 1px solid #dfdfdf; } th, td { padding: 2px 5px 2px 5px;}

這是一個示例,說明如何在 JavaScript 中從矩陣 mx n... 生成和讀取數據

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);

沒有行的純功能表(只是為了好玩)

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']
]));

我的 10cent 與 ar 是數組:

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

 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

對於那些不想使用 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測試

響應 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM