简体   繁体   English

JavaScript删除数组中的匹配项

[英]Javascript Delete matches in array

i want delete all matches in array, i have a function where i send a value, and through all matches in the array, and i delete if exist, but the array change for each splice , please look this is a litle example 我想删除数组中的所有匹配项,我有一个函数,在该函数中我发送一个值,并通过数组中的所有匹配项删除,如果存在,则删除,但是每个splice的数组都发生变化,请看这是一个小例子

var cars = ["Saab","Saab","Saab", "Volvo", "BMW","Volvo","Volvo", "BMW", "BMW", "BMW","Volvo"];

         for(j =0;j<cars.length;j++){                
                if(cars[j]=="Volvo"){
                  cars.splice(j, 1);
                }
         }
console.log(cars);

the result 结果

["Saab", "Saab", "Saab", "BMW", "Volvo", "BMW", "BMW", "BMW"]

Because indexes can get messed up when looping from beginning to end of an array and removing elements, usually it's best to go backwards : 因为从数组的开头到结尾循环并删除元素时索引可能会弄乱,所以通常最好倒退

var i = cars.length - 1;

while(i >= 0) {
  if(/* condition */) {
    cars.splice(i, 1);
  }

  i--;
}

I hate native loops though (no good reason, just a personal preference), so I prefer to use semantic forEach/reduce/map/filter . 我虽然讨厌本机循环(没有充分的理由,只是个人喜好),所以我更喜欢使用语义forEach/reduce/map/filter

filter is actually the most semantic here (next, maybe reduce ): filter实际上是这里最语义的(接下来,也许是reduce ):

var filteredCars = cars.filter(notVolvo);

function notVolvo(car) {
  return car !== 'Volvo';
}

If, for kicks and giggles, you wanted to use reduce , you could do: 如果想踢一下和咯咯地笑,请使用reduce ,可以这样做:

var reducedCars = cars.reduce(notVolvo, []);

function notVolvo(aggregate, car) {
  return car === 'Volvo' ? aggregate : aggregate.concat([car]);
}

The problem is that, when you use splice to remove an item, following items will be moved one position backwards so that there is no gap. 问题是,当您使用splice来删除项目时,以下项目将向后移动一个位置,因此没有间隙。

However, your loop increases the index variable independently on whether an item was removed or not. 但是,循环会根据是否删除项目独立增加index变量。 That means that, when you delete an item, the next one will be skipped. 这意味着,当您删除一项时,下一项将被跳过。

This can be fixed by counteracting the increment with a decrement: 可以通过减量抵消增量来解决此问题:

for (var i=0; i<cars.length; i++)
  if (cars[i] == "Volvo")
    cars.splice(i--, 1);

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

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