[英]Generate HTML table from 2D JavaScript array
In JavaScript, is it possible to generate an HTML table from a 2D array?在JavaScript中,是否可以从二维数组生成HTML表? The syntax for writing HTML tables tends to be very verbose, so I want to generate an HTML table from a 2D JavaScript array, as shown:
写HTML表的语法往往很冗长,所以我想从一个二维的JavaScript数组生成一个HTML表,如图:
[
["row 1, cell 1", "row 1, cell 2"],
["row 2, cell 1", "row 2, cell 2"]
]
would become:会成为:
<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>
So I'm trying to write a JavaScript function that would return a table from a 2D JavaScript array, as shown:所以我正在尝试编写一个 JavaScript function 将从二维 JavaScript 数组返回一个表,如下所示:
function getTable(array){
// take a 2D JavaScript string array as input, and return an HTML table.
}
Here's a function that will use the dom instead of string concatenation.这是一个将使用 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"]]);
This is pretty easy to do with a double for loop.使用双 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;
}
Another innerHTML-less version.另一个没有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;
}
An es6 version of Daniel Williams' answer: 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');
}
See the fiddle demo to create a table from an array .请参阅小提琴演示以从数组创建表。
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);
}
You can use it like this你可以像这样使用它
var tableData = [["r1c1", "r1c2"], ["r2c1", "r2c2"], ["r3c1", "r3c2"]];
createTable(tableData);
Based on the accepted solution:基于公认的解决方案:
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']
])
With a simple change it is possible to return the table as HTML element.通过简单的更改,可以将表格作为 HTML 元素返回。
One-liner using es6 reduce单行使用 es6 reduce
function makeTableHTML(ar) {
return `<table>${ar.reduce((c, o) => c += `<tr>${o.reduce((c, d) => (c += `<td>${d}</td>`), '')}</tr>`, '')}</table>`
}
Generate table and support HTML as input.生成表格并支持 HTML 作为输入。
Inspired by @spiny-norman https://stackoverflow.com/a/15164796/2326672灵感来自@spiny-norman https://stackoverflow.com/a/15164796/2326672
And @bornd https://stackoverflow.com/a/6234804/2326672还有@bornd https://stackoverflow.com/a/6234804/2326672
function escapeHtml(unsafe) {
return String(unsafe)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
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;
}
Test here with JSFIDDLE - Paste directly from Microsoft Excel to get table在此处使用 JSFIDDLE 进行测试 - 直接从 Microsoft Excel 粘贴以获取表格
I know this is an old question, but for those perusing the web like me, here's another solution:我知道这是一个老问题,但对于像我这样浏览网页的人来说,这是另一个解决方案:
Use replace()
on the commas and create a set of characters to determine the end of a row.在逗号上使用
replace()
并创建一组字符以确定行的结尾。 I just add --
to end of the internal arrays.我只是将
--
添加到内部数组的末尾。 That way you don't have to run a for
function.这样你就不必运行
for
函数。
Here's a JSFiddle: https://jsfiddle.net/0rpb22pt/2/这是一个 JSFiddle: https ://jsfiddle.net/0rpb22pt/2/
First, you have to get a table inside your HTML and give it an id:首先,您必须在 HTML 中获取一个表格并为其指定一个 id:
<table id="thisTable"><tr><td>Click me</td></tr></table>
Here's your array edited for this method:这是为此方法编辑的数组:
thisArray=[["row 1, cell 1__", "row 2, cell 2--"], ["row 2, cell 1__", "row 2, cell 2"]];
Notice the added --
at the end of each array.注意每个数组末尾添加的
--
。
Because you also have commas inside of arrays, you have to differentiate them somehow so you don't end up messing up your table- adding __
after cells (besides the last one in a row) works.因为您在数组中也有逗号,所以您必须以某种方式区分它们,以免最终弄乱您的表格 - 在单元格(除了连续的最后一个之外)工作后添加
__
。 If you didn't have commas in your cell, this step wouldn't be necessary though.如果您的单元格中没有逗号,则不需要此步骤。
Now here's your function:现在这是你的功能:
function tryit(){
document
.getElementById("thisTable")
.innerHTML="<tr><td>"+String(thisArray)
.replace(/--,/g,"</td></tr><tr><td>")
.replace(/__,/g,"</td><td>");
}
It works like this:它是这样工作的:
innerHTML
.innerHTML
。 document.getElementById("thisTable").innerHTML
"<tr><td>"
thisArray
as a String()
.thisArray
添加为String()
。 +String(thisArray)
--
that ends up before a new row with the closing and opening of data and row.--
在新行之前结束。 .replace(/--,/g,"</td></tr><tr><td>")
__
: .replace(/__,/g,"</td><td>")
.__
区分它们: .replace(/__,/g,"</td><td>")
。 Normally you'd just do .replace(/,/g,"</td><td>")
..replace(/,/g,"</td><td>")
。 As long as you don't mind adding some stray characters into your array, it takes up a lot less code and is simple to implement.只要您不介意在数组中添加一些杂散字符,它占用的代码就会少得多,而且实现起来也很简单。
If you don't mind jQuery, I am using this :如果你不介意 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>
This is holmberd answer with a "table header" implementation这是带有“表头”实现的 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, cell 2"]]); createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"], ["row 3, cell 1", "row 3, 单元格 2"]]);
Here's a version using template literals .这是使用模板文字的版本。 It
maps
over the data creating new arrays of strings build from the template literals, and then adds them to the document with insertAdjacentHTML
:它
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;}
Here is an example of how you can generate and read data from a matrix mx n... in JavaScript这是一个示例,说明如何在 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);
Pure functional table without new lines (Just for fun)没有换行的纯功能表(只是为了好玩)
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];
Usage用法
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;}
This is the exact copy of @Andy's answer with a slight modification so that the first cell of every row will be th
.这是@Andy 答案的精确副本,稍作修改,以便每一行的第一个单元格为
th
。
For those who do not want to use DOM对于那些不想使用 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);
}
tested with https://html5-editor.net使用https://html5-editor.net测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.