简体   繁体   English

Javascript使用对象变量从数组中删除对象

[英]Javascript remove object from array using object variable

So I am trying to use arrays and for demonstration purposes I have condensed the code using points as examples. 因此,我尝试使用数组,并且出于演示目的,我使用点作为示例浓缩了代码。 I want to create a point and push it to array and after doing stuff I want to remove the point from the array. 我想创建一个点并将其推入数组,并在完成操作后想从数组中删除该点。

var PointArray = [];
function CreatePoint(X,Y){
    this.x=X;
    this.y=Y;
    PointArray.push(this);
}
function RemovePoint(PointObject){
     //????
}
var xPoint = CreatePoint(10,10);
//do stuff
RemovePoint(xPoint);

I was looking at the ‍ Array.prototype manual and PointArray.Splice seems like a the closest but feels messy since it wants indexs. 我一直在寻找在Array.prototype手动和PointArray.Splice似乎是最接近的,但因为它希望指数法感觉凌乱。 Anyone have a clean way remove objects from array to shove into function RemovePoint ? 任何人都有一个干净的方法可以从数组中删除对象,然后将其推入功能RemovePoint

To find the index of something in an array, use indexOf : 要查找数组中某物的索引,请使用indexOf

function RemovePoint(PointObject){
  const index = PointArray.indexOf(PointObject);
  PointArray.splice(index, 1); // remove one item at index "index"
}

But if you're doing something like this, you might consider using a Set instead, which might be more appropriate if you want a collection, but the index of each object doesn't actually matter - then, you could just call PointSet.delete(PointObject); 但是,如果您正在执行这样的操作,则可以考虑改用Set ,如果您想要一个集合,这可能更合适,但是每个对象的索引实际上并不重要-然后,您可以调用PointSet.delete(PointObject); :

 const PointSet = new Set(); function CreatePoint(X,Y){ this.x=X; this.y=Y; PointSet.add(this); } function RemovePoint(PointObject){ PointSet.delete(PointObject); } console.log(PointSet.size); const xPoint = new CreatePoint(10,10); console.log(PointSet.size); RemovePoint(xPoint); console.log(PointSet.size); 

As comment notes, make sure to use new when calling a constructor like CreatePoint . 作为注释,请确保在调用诸如CreatePoint类的构造函数时使用new

Why not use filter to remove elements from PointArray 为什么不使用过滤器从PointArray中删除元素

var PointArray = [];
function CreatePoint(X,Y){
    this.x=X;
    this.y=Y;
    PointArray.push(this);
}
function RemovePoint(PointObject){
  PointArray = PointArray.filter(singlePoint=>!(singlePoint.x==PointObject.x && singlePoint.y==PointObject.y));
}
var xPoint = new CreatePoint(10,10);
var yPoint = new CreatePoint(20,20);
//do stuff
console.log(PointArray);
RemovePoint(xPoint);
console.log(PointArray);

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

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