簡體   English   中英

Splice()不會使數組為空

[英]Splice() does not make the array empty

我有數組x,y和z。 在迭代x時,基於條件我需要繼續從z中刪除元素。 這是我想要做的:

var x = ["test0", "test1", "test2"];
var y = ["test0", "test1", "test2"];
var z = ["test0", "test1", "test2"];

function myFunction(){
    for (var i=0; i<x.length; i++){
        for (var j=0; j<y.length; j++){
            if(x[i] == y[j]){
                z.splice(i,1);
            }
        }

    }
document.getElementById("demo").innerHTML = z;
}

在迭代結束時,z應該為空。 但它始終顯示我'test1'元素仍然存在。 由於正確的索引沒有被拼接,我試圖做z.splice(i--,1)但這也不起作用。

請告知解決此問題的最佳方法是什么?

如果你創建某種表格,這很容易理解。 問題是在第一次拼接之后,z的索引不像x和y的索引:

x[0] = j[0] : i = 0 -> z.splice(0, 1); - test0 is removed - z = ["test1", "test2"];
x[1] = j[1] : i = 1 -> z.splice(1, 1); - test2 is removed - z = ["test1"];
x[2] = j[2] : i = 2 -> z.splice(2, 1); - nothing is removed - z = ["test1"];

解:

function myFunction() {
    var removed = 0; // removed items counter
    for (var i = 0; i < x.length; i++) {
        for (var j = 0; j < y.length; j++) {
            if (x[i] == y[j]) {
                z.splice(i - removed, 1); // subtract removed counter from index
                removed++; // increment removed counter
            }
        }

    }
}

正如答案所說,你的問題是拼接z意味着索引和值不再在數組之間對齊。 從任何類型的列表中刪除元素時跟蹤已刪除索引的常見替代方法是從結尾迭代到開始,例如

 var x = ["test0", "test1", "test2"]; var y = ["test0", "test1", "test2"]; var z = ["test0", "test1", "test2"]; function myFunction(){ for (var i=x.length; i>0; ){ for (var j=y.length; j> 0; ){ if(x[--i] == y[--j]){ z.splice(i,1); } } } document.write('"' + z.join() + '"'); } myFunction(); 

如果你使用ES5引入的一些語法糖, reduceRight有助於減少代碼量:

function myFunction(){
  x.reduceRight(function(n, x, i) {
    y.reduceRight(function(n, y) {
      if (x == y) z.splice(i, 1)
    }, null);
  }, null)
  document.write('"' + z.join() + '"');
}

你可以通過跟蹤從z中刪除的元素的數量來解決它:

var numRemoved = 0;
for (var i=0; i<x.length; i++){
    for (var j=0; j<y.length; j++){
        if(x[i] == y[j]){
            z.splice( i - numRemoved++ , 1 );
        }
    }
}

您可以使用indexOf()找到當前索引,而不是跟蹤移動索引

for (var i=0; i<x.length; i++){
    for (var j=0; j<y.length; j++){
        if(x[i] == y[j]){
            z.splice( z.indexOf(x[i]) , 1 );
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM