在不知道索引的情况下从数组中删除“this”?

时间:2014-07-30 20:35:55

标签: javascript arrays oop

我有一个数组跟踪这样的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()函数中进行删除。

2 个答案:

答案 0 :(得分:4)

是的,您可以使用.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);

答案 1 :(得分:2)

也许尝试类似的事情:

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