Javascript 理解表函数
这些代码行从localstorage构建一个表,但我很难理解这两个Javascript 理解表函数,javascript,Javascript,这些代码行从localstorage构建一个表,但我很难理解这两个.foreach方法的含义,以及它们对表的意义。对表格的理解是为了一些学校作业 //Function creates table for employeeList function buildTable(data) { // creates variable "table" let table = document.createElement("table"); // Create table h
.foreach
方法的含义,以及它们对表的意义。对表格的理解是为了一些学校作业
//Function creates table for employeeList
function buildTable(data) {
// creates variable "table"
let table = document.createElement("table");
// Create table head and body
table.appendChild(document.createElement("thead"));
table.appendChild(document.createElement("tbody"));
let fields = Object.keys(data[0]);
let headRow = document.createElement("tr");
fields.forEach(function (field) {
let headCell = document.createElement("th");
headCell.textContent = field;
headRow.appendChild(headCell);
});
table.querySelector("thead").appendChild(headRow);
data.forEach(function (object) {
let row = document.createElement("tr");
fields.forEach(function (field) {
let cell = document.createElement("td");
cell.textContent = object[field];
if (typeof object[field] == "number") {
cell.style.textAlign = "left";
}
row.appendChild(cell);
});
table.querySelector("tbody").appendChild(row);
});
return table;
第一个foreach将根据
data
数组中第一个对象的键生成表头
第二个foreach将为
数据
数组中的每个对象呈现一个表行。普通表的结构类似于:
<table>
<th>
<td>Heading cell</td>
</th>
<tr>
<td>Normal cell</td>
</tr>
</table>
标题单元格
正常细胞
th
元素表示标题行,tr
元素表示正常行
2foreach
循环用于将数据添加到表中:
- 第一个循环处理第一行数据
,该行进入页眉,因为它包含标签李>data[0]
- 第二个循环处理正常行中的其余数据
table.querySelector(“thead”)
和table.querySelector(“tbody”)
检索在每个循环中生成的作为各自行的父级的DOM元素