从数组中删除项目的最有效方法?

Evi*_*mes 5 javascript

我有两个数组。如果用户添加产品,我们会将其放入 ProductArray 中。如果他们删除该产品,我们会将其添加到 ProductArrayRemove 数组中,并将其从产品数组中删除。(我们需要知道已添加的产品以及已删除的产品。这需要冗余。)

ProductArray = JSON.parse(ProductArray);
ProductArrayRemove = JSON.parse(ProductArrayRemove);
Run Code Online (Sandbox Code Playgroud)

当我将项目添加到数组时,我只需这样做:

 ProductArray.push(ItemID);
 ProductArrayRemove.push(ItemID);
Run Code Online (Sandbox Code Playgroud)

但是当我删除它时,我必须这样做:

var len = ProductArray.length;
for (i = 0; i < len; i++) {
    ProductID = ProductArray[i];
    if (ProductID == ItemID) {
        ProductArray.splice(i,1);
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

看来应该有更好的方法来完成这个任务。

是否有更有效的方法从数组中删除单个项目(始终是整数)?

jfr*_*d00 1

删除项目速度超快的一种不同想法是仅维护单个项目列表,并为每个项目设置一个属性来确定是否删除该项目。

然后要删除一个项目,您所做的就是设置它的 property obj.removed = true

再次将其添加回来,您只需更改该属性的值即可。

要仅迭代添加的项目,只需跳过具有该.removed == true属性的项目即可。要仅迭代已删除的项目,只需执行相反的操作。这里有几个迭代器:

ProductArray.iterateAdded = function(fn) {
    for (var i = 0; i < this.length; i++) {
        if (!this[i].removed) {
            if (fn.call(this, i, this[i]) === false) {
                return;
            }
        }
    }
}

ProductArray.iterateRemoved = function(fn) {
    for (var i = 0; i < this.length; i++) {
        if (this[i].removed) {
            if (fn.call(this, i, this[i]) === false) {
                return;
            }
        }
    }
}

ProductArray.getSubLength = function(removed) {
    var cnt = 0;
    for (var i = 0; i < this.length; i++) {
        if (removed == this[i].removed) {
            ++cnt;
        }
    }
    return(cnt);
}
Run Code Online (Sandbox Code Playgroud)

并且,您可以像这样使用它们:

ProductArray.iterateAdded(function(i, val) {
   // this is the array
   // i is the index we are iterating
   // val is the array element we are iterating this[i]
   // put code here
});
Run Code Online (Sandbox Code Playgroud)