从数组中查找并删除元素

Find and remove element from array

本文关键字:删除 元素 查找 数组      更新时间:2023-09-26

如果我有一个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

您可以使用

.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);
    }
}

就个人而言,我喜欢在过滤器方法中使用可重用的函数:

//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]

jQuery的创建者John Resig创建了一个非常方便的Array.move方法,我总是在项目中使用它。

// 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);

---编辑----

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

像这样使用代码来删除特定值。

这是一个基于索引的删除函数

function  remove(array, index){
     for (var i = index; i < arr.length-1; i++) {
          array[i] = array[i+1];    
      }
}

基本上,这样做是将所有元素从索引移动到"左"。不太确定拼接是如何工作的,但我猜它的工作方式完全相同。

将该函数添加到代码后,您所要做的就是。

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

我更喜欢做这样的事情:

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

myaraay.splice() 要删除,myarray.indexOf() 给出数字或任何你想要从数组内部删除的内容。这是最简单的方法,无需循环。:)