简体   繁体   English

从JavaScript数组中删除底片

[英]Removing negatives from JavaScript array

This is not removing negative integers from an array. 这不是从数组中删除负整数。 I can't figure out why not... 我不知道为什么不...

for(var ii = 0; ii < diffs.length; ii++) {
     if(Number(diffs[ii]) < 0) {
       diffs.splice(ii, 1);
     }
   }

You can't traverse the array upwards from 0 when you are modifying the array during the traversal because removing the current element will move the other elements down in the array and cause you to skip the next element. 在遍历期间修改数组时,不能从0向上遍历该数组,因为删除当前元素将使数组中的其他元素向下移动,并导致您跳过下一个元素。

A common way to solve this is to traverse the array elements in reverse order because the elements that are repositioned by removing the current element are ones that you have already traversed, not the ones the for loop is still going to process next: 解决此问题的一种常见方法是以相反的顺序遍历数组元素,因为通过删除当前元素而重新定位的元素是您已经遍历的元素,而不是for循环接下来将要处理的元素:

for(var ii = diffs.length - 1; ii >= 0; ii--) {
    if(Number(diffs[ii]) < 0) {
        removed.push(diffs[ii]);
        diffs.splice(ii, 1);
    }
}

You also have to push the removed item BEFORE you remove it from the array. 您还必须先将已删除的项目从阵列中删除,然后再进行推送。

You have two problems: 1) When you remove items in the array, you have to make sure you don't increment the counter (this can be avoided by counting from the end). 您有两个问题:1)在删除数组中的项目时,必须确保您不增加计数器(可以通过从末尾开始计数来避免这种情况)。 2) You have to store the result from splice and then add it to the removed array 2)您必须存储来自拼接的结果,然后将其添加到删除的数组中

for(var ii = diffs.length - 1; ii >= 0; ii--) {
    if(+diffs[ii] < 0) { // use the unary plus operator to convert to a number, just in case
        removed.push(diffs.splice(ii, 1)[0]); //splice returns an array - get the first and only element in it
    }
}

When removing item while traversing an array forward, you will need to adjust the loop variable or you skip the next element. 在向前遍历数组时删除项目时,您需要调整循环变量或跳过下一个元素。 The other possibility is to traverse backwards. 另一种可能性是向后移动。

for (var i=0; i<diffs.length; i++)
    if (Number(diffs[i]) < 0)
        diffs.splice(i--, 1);

// OR

for (var i=diffs.length-1; i>=0; i--)
    if (Number(diffs[i]) < 0)
        diffs.splice(i, 1);

It might be easier (and maybe even faster) to create a new array and overwrite the diffs variable with it. 创建一个新数组并用它覆盖diffs变量可能更容易(甚至更快)。 This works very elegant with the filter() method : 使用filter()方法可以非常优雅地工作:

var diffs = diffs.filter(function(diff) { return Number(diff) >= 0; });

The index can be fixed also like this: 索引也可以这样固定:

for (ii = 0; ii < diffs.length; ii++) {
    if (Number(diffs[ii]) < 0) {
        removed.push(diffs[ii]);
        diffs.splice(ii, 1);
        ii--;
    }
}
console.log(diffs);
console.log(removed);

fiddle 小提琴

As now I see, posted this answer too late again :) 如我现在所见,再次发布此答案为时已晚:)

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

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