简体   繁体   English

Javascript中的Splice Function将4个空行添加到我的数组中吗?

[英]Splice Function in Javascript is adding 4 empty rows to my array?

I want to remove all the rows whose length is less than some value. 我要删除长度小于某个值的所有行。 I'am using Splice function in javascript to do this. 我正在使用javascript中的Splice函数来执行此操作。

for (var i = 0; i < table.length; i++) {

    if (table[i].length<=6) {
         table.splice(i, 1);
    }
}

but two rows with length:0 are being added at the beginning and at the end of my array this is the actual array extra rows added after being spliced whis is this happening? 但是在我的数组的开头和结尾处添加了长度为0的两行, 这是 在进行拼接后 实际 添加的额外 数组 吗? how can i get rid of it? 我如何摆脱它?

I suggest to splice from the end to start, because if an element is spliced, the following elements are move a place in front of the array. 我建议从头到尾进行拼接,因为如果拼接了一个元素,则以下元素将在数组前面移动一个位置。

 var table = [ [0, 1, 2, 3, 4, 5], [], [0], [], [], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0], [0], [], [], [1] ], i = table.length; while (i--) { if (table[i].length <= 6) { table.splice(i, 1); } } console.log(table); 

Try with this: 试试这个:

for (var i = 0; i < table.length; i++) {

    if (table[i].length<=6) {
        table.splice(i, 1);
        i--;
    }
}

After deleting a row you have to decrease the index to the array because the elements of the array have been shifted by the precious removal. 删除一行后,您必须减少对该数组的索引,因为该数组的元素已通过宝贵的删除操作而移动了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM