简体   繁体   English

从数组中删除对象

[英]removing objects from array

i have an array = [] and it contains objects... obj, obj, obj .我有一个array = []它包含对象... obj, obj, obj I have to remove obj two , but i don't know the index... so how can i remove obj.我必须删除obj two ,但我不知道索引...所以我怎样才能删除 obj. the name of the object is also same. object 的名称也相同。

I hope it helps you:我希望它可以帮助你:

function removeByElement(array,obj) {
  for(var i=0; i<array.length;i++ ) { 
    if(array[i]==obj) {
      array.splice(i,1); 
      break;
    }
  } 
}

EDIT: breaking the loop.编辑:打破循环。

The ES5 way to do this is with Array.filter执行此操作的 ES5 方法是使用Array.filter

 myarray = myarray.filter(function(val, index, a) {
    return (val !== obj);
 });

See the MDN page linked above for a version to use if you don't have ES5.如果您没有 ES5,请参阅上面链接的 MDN 页面以获取要使用的版本。

Technically this creates a new array, rather than modify the original array.从技术上讲,这会创建一个新数组,而不是修改原始数组。 However splice as proposed in other answers isn't particularly efficient anyway since it has to renumber all of the indices above each matching element, and will do so over and over if there's more than one match.然而,在其他答案中提出的splice并不是特别有效,因为它必须重新编号每个匹配元素上方的所有索引,并且如果有多个匹配项,它将一遍又一遍地这样做。

function removeObject(obj, arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === obj) {
      arr.splice(i, 1);
      break;
    }
  }
}

if you do not know the index, you have to iterate on all elements and check each if they are the one you look for, and then delete it.如果您不知道索引,则必须迭代所有元素并检查每个元素是否是您要查找的元素,然后将其delete

var len = your_array.length;
for(var i=0; i<len;i++){
  if(typeof(your_arry[i])=='classOfTypeYouLookFor'){// OR if(your_array[i].property_of_class && your_array[i].property_of_class==some_specific_value){
      delete(your_arry[i]);
  }
}

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

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