我有数组 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
}
}
}
}
关于javascript - Splice() 不会使数组为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32161292/