从数组中查找并移除元素

5
如果我有一个JavaScript数字数组。
[1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1]

我想要搜索数组并移除特定的数字,例如4,得到:

[1, 2, 5, 7, 5, 7, 9, 2, 1]

什么是最好的方法呢?

我想它可能看起来像这样

for(var i = 0; i < myarray.length; i++) {
    if(myarray[i] == 4) {
        myarray.remove(i)
    }
}

但是数组没有remove函数。另外,如果我从数组中删除一个元素,它会破坏我的i(索引), 除非我进行纠正。


可能是从数组中删除特定元素?的重复问题。 - j08691
1
...或者 delete myarray[i] - 别忘了在删除时跳过迭代的增量! - Pointy
@LightStyle 哦,那看起来很有趣。Vincent Piel,我不完全理解它们之间的区别。 - user2748139
2
只是简单地倒数比跳过增量容易得多。 - cage rattler
ROTFL 大笔误!感谢 @dc5 指出来! - Niccolò Campolungo
显示剩余3条评论
5个回答

8

您可以使用.splice()从数组中删除一个或多个项,如果您从数组的后面向前迭代,则在删除项时不会使索引混乱。

var arr = [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1];
for (var i = arr.length - 1; i >= 0; i--) {
    if (arr[i] == 4) {
        arr.splice(i, 1);
    }
}

6

个人而言,我喜欢使用可重用函数和过滤方法:

//generic filter:
function without(a){return this!=a;}


//your data:
var r= [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1];

//your data filtered against 4:
var no4=r.filter(without, 4);

//verify no 4s:
alert(no4); //shows: "1,2,5,7,5,7,9,2,1"

如果您希望修改原始数组,则可以直接将新值覆盖并推入旧数组:
 function without(a){return this!=a;}
 var r= [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1],  //orig
    r2=r.slice(); //copy
 r.length=0; //wipe orig
 [].push.apply( r, r2.filter(without, 4)); //populate orig with filtered copy
 r; // == [1, 2, 5, 7, 5, 7, 9, 2, 1]

1
这是一个很好的解决方案 - 但你的格式让我感到有些焦虑。 - flaky

1
我更喜欢像这样做:


removeEmail(event){
   myarray.splice(myarray.indexOf(event.target.id), 1)
}

myarray.splice()将要移除,myarray.indexOf()给出从数组中删除的数字或其他内容。这是最简单的方法,无需循环。


1
jQuery 的创始人 John Resig 创建了一个非常方便的 Array.remove 方法,我在我的项目中总是使用它。
// Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };

所以,您可以像这样使用您的代码:
// Remove the second item from the array
myarray.remove(1);
// Remove the second-to-last item from the array
myarray.remove(-2);
// Remove the second and third items from the array
myarray.remove(1,2);
// Remove the last and second-to-last items from the array
myarray.remove(-2,-1);

---Edit----

for(var i = 0; i < myarray.length; i++) {
    if(myarray[i] == 4) {
        myarray.remove(i);
    }
}

使用以下代码以删除特定值。

OP想要删除具有特定值的元素。 - dc5
您在编辑中添加的代码无法工作,因为当您移除一个项目时,数组索引会发生变化,从而跳过评估某些项目。 - jfriend00
所以你可以使用splice()!这个函数的名称、参数名称和结果并不明显。我的建议是只使用splice(index,length)。 - PabloWeb18

1
这是一个基于索引的删除函数。
function  remove(array, index){
     for (var i = index; i < arr.length-1; i++) {
          array[i] = array[i+1];    
      }
}

基本上,这个功能是将所有元素从索引向“左”移动。不太确定splice的工作原理,但我猜它的工作方式完全相同。
在将该函数添加到代码后,您只需要执行以下操作。
for(var i = 0; i < myarray.length; i++) {
    if(myarray[i] == 4) {
       remove(myarray,i);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接