簡體   English   中英

在Java / HTML中使用2D數組在表中動態創建/實現數據

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

我試圖實現的目標是根據2D數組中的信息動態創建一個包含數據的表。 我已經看到了使用1D數組創建表的示例,但似乎無法用2D創建表。 此外,一旦創建了該表,我就需要能夠對其進行操作,例如刪除包含無關緊要信息的行等。我喜歡為此使用嵌套的for循環。 這需要使用Javascript / HTML創建。 該表例如:

|item   | price | description|

|chicken | $20  | yummy |

並且數組[0] [0]是雞肉,[0] [1]是$ 20,[0] [2]很好吃。 任何幫助/潛在客戶表示贊賞!

進行嵌套的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

這將為您創建一個具有數組值的表。

下面使用嚴格的dom操作來構建您的表,創建必要的元素(即HTML,TBODY,THEAD,TR,TD,TH),並在循環過程中構建結構。

這樣做的性能可以提高,但這取決於表(及其表)的大小。 除非常大的表外,在大多數情況下,執行字符串連接然后綁定到dom會更快。 使用字符串插值還有其他缺點,例如轉義某些字符(dom操縱為您處理)。

只有您可以確定桌子的大小,然后做出判斷。

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

字符串串聯

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

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

您可以像這樣修改它

 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