我试图弄清楚这段代码的作用。我确实了解整体概念,使用localStorage通过DOM方法构建表。我不太确定表格是否从中获取数据? buildtable()如何从Employee数据中知道自己正在构建它?了解是针对学校家庭作业的:)

if(localStorage.getItem("Employee") == null) {
    var employeeList = [];
    employeeList.push (new Employee("Simon", "Male", "HR", 1999, "[email protected]"));
    employeeList.push (new Employee("Mads", "Male","IT", 1999,  "[email protected]"));
    employeeList.push (new Employee("Jessica", "Female", "Sales",1998, "[email protected]"));
    employeeList.push (new Employee("Benjamin", "Male","IT", 1997, "[email protected]"));

    var employeeListString = JSON.stringify(employeeList);
    localStorage.setItem("Employee", employeeListString);
    document.querySelector("#employees").appendChild(buildTable(employeeList));
} else {
    var employeeList = JSON.parse(localStorage.getItem("Employee"));
}

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

    }

document.querySelector("#employees").appendChild(buildTable(employeeList));

最佳答案

buildTable(data)data参数获取数据,该参数由以下行提供:

buildTable(employeeList)

因此,表从employeeList数组获取其数据。

表列标题是从构成数组的对象的属性名称填充的。由于数组中每个对象的这些都是相同的(即每个员工都具有相同的数据结构),因此只需要读取第一个对象[0]

因此,如果data看起来像这样:

[
    {
        foo: 'bar',
        bar: 'foo'
    },
    {
        foo: 'bar2',
        bar: 'foo2'
    }
]


...我们可以使用第一个(或任何一个)对象来生成列标题。

09-19 04:01