写入此功能以在表中删除行/对象的更快方法



所以,我拥有此功能,在更新后,从表中删除了元素。该函数称为foo(),输入一个参数。

foo(obj);

此对象OBJ在类型数组的称为消息中具有一个子字段。因此,它看起来像这样:

obj.messages = [...];

此外,在OBJ.Messages内部,每个元素都包含一个具有另一个子字段ID的对象。因此,这看起来像:

obj.messages = [{to:"You",from:"Me",id:"QWERTY12345.v1"}, ...];

现在,除了参数外,我还有一个实时表,该表也由function foo引用。它使用我称为otable的数据表元素。然后,我抓住了otable的行,然后将它们复制到一个名为thecurrenttable的数组中。

var theCurrentTable = oTable.$('tr').slice(0);

现在,它变得棘手的地方是当我查看数组thecurrenttable时,我返回的值出现了。

theCurrentTable = ["tr#messagesTable-item-QWERTY12345_v1", ...];

下面的循环显示了我如何尝试显示问题。虽然(看似)起作用,但该功能本身可以包含1000多条消息,这是一个非常昂贵的功能。它要做的就是检查当前显示的表是否具有参数中给出的元素,如果不是特定的元素,则将其删除。我如何更好地编写此功能?

var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
for(var idx = 0; idx < theCurrentTable.length; idx++){ // through display
    var displayID = theCurrentTable[idx].id.replace('messagesTable-item-','').replace('_','.');
    var deletionPending = true;
    for(var x = 0; x < theReceivedMessages.length; x++){
        var messageID = theReceivedMessages[x].id;
        if(diplayID == messageID){
            console.log(displayID+' is safe...');
            deletionPending = false;
        }
    }
    if(deletionPending){
        oTable.fnDeleteRow(idx);
    }
}

我想我了解您的问题。您的<tr>元素具有id,该元素应与您的消息中的项目ID匹配。

首先,您应该从obj参数

提取所需的消息ID值
var ids = obj.messages.map(function (m) { return '#messagesTable-item-' + m.id; });

这将为您提供所需的所有行ID,然后将数组一起使用jQuery选择您不需要的行并删除它们。

$('tr').not(ids.join(',')).remove();

注意:array.prototype.map()函数仅来自IE9,因此您可能需要使用jquery.map()。

您可以创建一组您拥有的消息ID值,因此您以后可以检测到给定ID是否在此集合中以恒定时间为单位。

这是看起来的样子:

var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
// Pre-processing: create a set of message id values:
var ids = new Set(theReceivedMessages.map( msg => msg.id ));
theCurrentTable.forEach(function (row, idx) { // through display
    var displayID = row.id.replace('messagesTable-item-','').replace('_','.');
    // Now you can skip the inner loop and just test whether the Set has the ID:
    if(!ids.has(displayId)) {
        oTable.fnDeleteRow(idx);
    }
});

所以现在的时间复杂性不再是 o(n.m) - 其中 n 是消息的数量,而 m 数字表行 - 但是 o(n m),对于 n m 的巨大值可能会产生很大的不同。p>注意:

如果 thecurrenttable 不是一个真正的数组,那么您可能需要像以前一样使用for循环,否则使用Array.from(theCurrentTable, function ...)

其次, otable.fndeleterow的实现可能是您需要先删除最后一行,因此 idx 仍然指向原始行号。在这种情况下,您应该从末端开始扭转循环。

最新更新