简体   繁体   English

在Java / HTML中使用2D数组在表中动态创建/实现数据

[英]Dynamically Creating / Implementing Data in A Table with a 2D Array in Javascript/Html

The goal I am trying to achieve is to dynamically create a table with data based off of the info from a 2D array. 我试图实现的目标是根据2D数组中的信息动态创建一个包含数据的表。 I've seen examples of table creation with 1D arrays, but I can't seem to wrap around creating it with 2D. 我已经看到了使用1D数组创建表的示例,但似乎无法用2D创建表。 Furthermore, once this table is created, I need to be able to manipulate it, for example deleting a row with insignificant information etc. I like to use a nested for loop for this. 此外,一旦创建了该表,我就需要能够对其进行操作,例如删除包含无关紧要信息的行等。我喜欢为此使用嵌套的for循环。 This needs to be created with Javascript / Html. 这需要使用Javascript / HTML创建。 The table for example : 该表例如:

|item   | price | description|

|chicken | $20  | yummy |

And the array [0][0] is chicken, [0][1] is $20, [0][2] is yummy. 并且数组[0] [0]是鸡肉,[0] [1]是$ 20,[0] [2]很好吃。 Any help / leads are appreciated!. 任何帮助/潜在客户表示赞赏!

Do a nested for loop: 进行嵌套的for循环:

let myArray = [['chicken', '$20', 'yummy']];
let myTable = '<table>';

for(let row = 0; row < myArray.length; row++){

    myTable += '<tr>'; // Create a row
    for(let col = 0; col < myArray[row].length; col++){
        myTable += `<td>${myArray[row][col]}</td>`; // Create a cell with the data
    }
    myTable += '</tr>'; // Close the row

}

myTable += '</table>'; // Finally close the table

This should create you a table with the array values. 这将为您创建一个具有数组值的表。

Below uses strictly dom manipulation to build your table, creating the necessary elements (ie HTML, TBODY, THEAD, TR, TD, TH) and building the structure over the course of a loop. 下面使用严格的dom操作来构建您的表,创建必要的元素(即HTML,TBODY,THEAD,TR,TD,TH),并在循环过程中构建结构。

The performance of doing so can be improved, but this depends on how big your table (and the content of it) is. 这样做的性能可以提高,但这取决于表(及其表)的大小。 Doing string concatenation and then binding to the dom in most cases will be faster, except for very large tables. 除非常大的表外,在大多数情况下,执行字符串连接然后绑定到dom会更快。 There are also other disadvantages to using string interpolation, such as escaping certain characters (dom manipulation handles this for you). 使用字符串插值还有其他缺点,例如转义某些字符(dom操纵为您处理)。

Only you can determine how big/small your table is and make the judgement. 只有您可以确定桌子的大小,然后做出判断。

DOM Manipulation DOM操作

 'use strict'; let arr = [ ['item', 'price', 'description'], ['chicken', '$20', 'yummy'] ], doc = document; // Create DOM elements let table = doc.createElement('table'), thead = doc.createElement('thead'), tbody = doc.createElement('tbody'); // Create cells and rows arr.forEach((data, i) => { let tr = doc.createElement('tr'); let container = tbody; let cell_type = 'td'; if (i == 0) { container = thead; cell_type = 'th'; } // Create and attach cells to row data.forEach(text => { let td = doc.createElement(cell_type); td.appendChild(doc.createTextNode(text)); tr.appendChild(td); }); // Attach TR to THEAD/TBODY container.appendChild(tr); }); // Attach THEAD/TBODY to TABLE table.appendChild(thead); table.appendChild(tbody); // Append Table to Document doc.querySelector('body').appendChild(table); 
 table { border: 1px solid #999; border-collapse: collapse; margin-top: 2rem; } td, th { border: 1px solid #ccc; border-collapse: collapse; padding: .25rem; } th { text-transform: capitalize; } 

String Concatenation 字符串串联

 'use strict'; let arr = [ ['item', 'price', 'description'], ['chicken', '$20', 'yummy'] ]; // Build Rows let rows = arr.map((data, i) => { let type = i == 0 ? 'th' : 'td'; let cells = data.map(text => `<${type}>${text}</${type}>`) return `<tr>${cells.join('')}</tr>`; }); // Build Table let table = `<table> <thead>${rows.shift()}</thead> <tbody>${rows.join('')}</tbody> </table>`; // Append Table to Document document.querySelector('body').innerHTML += table; 
 table { border: 1px solid #999; border-collapse: collapse; margin-top: 2rem; } td, th { border: 1px solid #ccc; border-collapse: collapse; padding: .25rem; } th { text-transform: capitalize; } 

Do it dynamically with Vanilla and ES6 使用Vanilla和ES6动态执行

 const food = [{ Item: "chicken", Price: "$20", Description: "buck,buck,,,,, buck,,, buckAHHHH yumm" }, { Item: "Beef", Price: "$20", Description: "Moo yumm" }, { Item: "Dog", Price: "$20", Description: "woof-woof yumm" }, { Item: "Cat", Price: "$20", Description: "meow-meow yumm" }]; function tableCreate(items) { let lables = items.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []); items.unshift(lables); let body = document.body, tbl = document.createElement('table'); tbl.style.width = '100px'; tbl.style.border = '1px solid black'; for (let [i, index] of items.entries()) { let tr = tbl.insertRow(); for (let j in items[i]) { let td = tr.insertCell(); td.appendChild(document.createTextNode(items[i][j])); td.style.border = '1px solid black'; } } body.appendChild(tbl); tbl.rows[0].style.fontWeight = 'bold'; } tableCreate(food); 

And you can modify it like so 您可以像这样修改它

 const food = [{ Item: "chicken", Price: "$20", Description: "buck,buck,,,,, buck,,, buckAHHHH yumm" }, { Item: "Beef", Price: "$20", Description: "Moo yumm" }, { Item: "Dog", Price: "$20", Description: "woof-woof yumm" }, { Item: "Cat", Price: "$20", Description: "meow-meow yumm" }]; function tableCreate(items) { let lables = items.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []); items.unshift(lables); let body = document.body, tbl = document.createElement('table'); tbl.style.width = '100px'; tbl.style.border = '1px solid black'; for (let [i, index] of items.entries()) { let tr = tbl.insertRow(); for (let j in items[i]) { let td = tr.insertCell(); td.appendChild(document.createTextNode(items[i][j])); td.style.border = '1px solid black'; } } body.appendChild(tbl); tbl.rows[0].style.fontWeight = 'bold'; } const modify = { remove(from, val) { for (let [i, product] of from.entries()) { if (product.Item === val) { console.log(i) from.splice(i, 1); console.log(from) } } }, removeOnLengthsLargerThan(from, val) { for (let [i, product] of from.entries()) { if (product.Description) { if (product.Description.length > val) { from.splice(i, 1); } } } }, shorten(from, val) { for (let [i, product] of from.entries()) { if (product.Description) { if (product.Description.length > val) { product.Description = product.Description.substr(0, val); } } } } } modify.shorten(food, 10); console.log('shorten',food); modify.remove(food, 'chicken'); console.log('remove',food); modify.removeOnLengthsLargerThan(food, 10) console.log('removeOnLengthsLargerThan',food); tableCreate(food); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM