javascript 仅使用对象的引用从数组中删除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17657706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:06:16  来源:igfitidea点击:

remove object from array with just the object's reference

javascriptarrays

提问by frenchie

Suppose I have an array of objects called MyArrayand that a certain function returns a reference for a particular element within that array; something like this:

假设我调用MyArray了一个对象数组,并且某个函数返回对该数组中特定元素的引用;像这样:

MyArray = [Object1, Object2, ..., Objectn];

function DoWork() {

   var TheObject = GetTheObject(SomeParamter);
}

At this point, TheObjectpoints to a certain element in the array. Suppose I want to remove this element from MyArray, is this possible without having to reloop through the array to get the index of the element?

此时,TheObject指向数组中的某个元素。假设我想从 中删除这个元素MyArray,这可能不需要重新循环遍历数组来获取元素的索引吗?

I'm looking for something like splice that would work with the reference to the element rather than the index of the element.

我正在寻找类似 splice 的东西,它可以与对元素的引用而不是元素的索引一起使用。

回答by Jon

Simply use Array.prototype.indexOf:

只需使用Array.prototype.indexOf

let index = MyArray.indexOf(TheObject);
if(index !== -1) {
  MyArray.splice(index, 1);
}

Keep in mind that if targeting IE < 9 you will need to introduce a polyfill for indexOf; you can find onein the MDN page.

请记住,如果针对 IE < 9,您将需要为indexOf; 您可以在 MDN 页面中找到一个