删除“this"从不知道索引的数组

Delete "this" from array without knowing index?

本文关键字:不知道 索引 数组 this quot 删除      更新时间:2023-09-26

我有一个数组跟踪javascript对象,像这样:

var myArray = [];

对象看起来像这样:

Main.prototype.myObject = function (x, y) {
    this.x = x;
    this.y = y;
    this.moveObject = function () {
        // Change x, y coordinates
        if (someEvent) {
            // Delete myself
            // deleteObject();
        }
    };
    this.deleteObject = function () {
        // Delete code
    }
};

对象像这样被压入数组:

myArray.push(new main.myObject(this.x, this.y));

现在,有没有一种方法可以删除具有this的对象的特定实例,而不知道它在myArray中的索引?

我宁愿保持for循环干净,并在已经存在的moveObject()函数中进行删除。

是的,您可以使用.indexOf请求索引:

//  find the index in the array (-1 means not found):
var index = myArray.indexOf(myObj);
//  remove the element at that index, if found:
if(index > -1) myArray.splice(index, 1);

也许可以试试:

this.deleteObject = function() {
    var idx = myArray.indexOf(this);
    if (idx >= 0) {
        myArray.splice(idx, 1);
    }
}