Javascript使用对象变量

时间:2018-08-25 03:50:25

标签: javascript

因此,我尝试使用数组,并且出于演示目的,我使用点作为示例浓缩了代码。我想创建一个点并将其推入数组,并在完成操作后想从数组中删除该点。

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

我一直在浏览‍ Array.prototype手册,而PointArray.Splice似乎是最接近的手册,但由于它需要索引,所以感觉很混乱。任何人都有一种干净的方法可以从数组中删除对象以使用RemovePoint函数吗?

2 个答案:

答案 0 :(得分:4)

要查找数组中某物的索引,请使用indexOf

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

但是,如果您正在执行类似的操作,则可以考虑使用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);

作为注释,请确保在调用new之类的构造函数时使用CreatePoint

答案 1 :(得分:0)

为什么不使用过滤器从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);