在Javascript中构建任意长度表的标准方法

问题描述 投票:0回答:1

我正在从websocket(实时流)接收数据,并尝试将其放入表中。我目前正在使用以下代码:

var table = document.getElementById("websocket-data");
function writeToScreen(message) {
    var new_row = table.insertRow(0);
    var cell1 = new_row.insertCell(0);
    var cell2 = new_row.insertCell(1);
    var obj = JSON.parse(message.data);
    console.log(obj.value);
    cell1.innerHTML = obj.id;
    cell2.innerHTML = obj.value;
}

这样可以工作,并为每个JSON数据包创建一个新行。我正在寻找的功能是:收到JSON后,如果id不在表中,则创建一个具有id和value的行,但是,如果id已经在表中,只需更新该值即可。我有几种方法可以做到这一点,但我想知道“正确”的做法是什么。我想也许数据应该进入一个数组,然后数组应该填充表,但这将涉及每次数组更改时重新填充整个表...我很乐意在必要时使用JQuery或类似的。

javascript json
1个回答
0
投票

您可以使用数组并按照您所说的那样重新填充表格,如果表格只是很小,那么您可能不会遇到问题。

许多可能的替代方法是使用id作为键在后台维护一个对象,然后将值和表行索引存储为值。

就像是:

var tableStore = {};

function recieveMessage(message) {
    var obj = JSON.parse(message);

    // if the id is not in the tableStore, add it!
    if (tableStore[obj.id] === undefined) {
        // insert new row into table and save the index into `newTableRowIndex`

        // store a blank value (updated below) and the index in the table where it will be displayed
        tableStore[obj.id] = {value: undefined, tableIndex: newTableRowIndex};
    }

    // if the value recieved is different than the stored value, update the row
    if (obj.value !== tableStore[obj.id].value) {
        tableStore[obj.id].value = obj.value; // store the new value
        var row = getTableRow(tableStore[obj.id].tableIndex); // your own function to get the row based on index
        // update the row to display the new information
    }
}

这可以改进,使组织更有条理,但你应该得到这个想法。

这样,如果收到的新信息与已存储的旧信息不同,它只会更新显示中的任何内容。

如果表有可能变得非常大,这种方式也应该比使用数组更好,因为每次都不需要搜索整个数组以查看id是否已经存储。您只需使用id直接访问tableStore条目。

© www.soinside.com 2019 - 2024. All rights reserved.