【问题标题】:Delete "this" from array without knowing index?在不知道索引的情况下从数组中删除“this”?
【发布时间】:2014-07-30 20:35:54
【问题描述】:

我有一个数组来跟踪这样的 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));

现在,有没有一种方法可以在不知道 myArray 中的索引的情况下使用 this 删除对象的特定实例?

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

【问题讨论】:

  • 您不能从对象内部删除对象。你需要在其他地方循环遍历数组,找到你想要的对象,然后拼接对象什么的。

标签: javascript arrays oop


【解决方案1】:

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

【讨论】:

  • 我认为这就是 OP 的要求......但很难说
  • @Oscar 似乎无法正常工作。 myArray.indexOf(myObject) 杀死脚本,而 myArray.indexOf(main.myObject) 不做任何事情。并且 console.log(index) 总是返回 -1。有什么线索吗?
  • indexOf 中的“myObject”应该是包含您要查找的对象实例的实际变量。如果它找不到你放在 .indexOf() 中的变量,它将输出 -1,这解释了你的 console.log 输出。希望有帮助!
  • @Oscar 那是我的问题,对象是用 new main.myObject(x, y) 创建的,这是我在 for 循环之外的唯一标识符。对象都是一样的。我还能这样做还是应该只使用 myArray[i]?
  • 哦,现在我想我明白了这个问题。在您的方法deleteObject 中,您正在寻找myArray 数组中this 对象的索引?在这种情况下,您实际上可以将this 传递给.indexOf(),因为this 是对实例本身的引用。那有意义吗?下面是函数的样子:jsfiddle.net/m65Jr
【解决方案2】:

也许可以试试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2013-08-06
    • 2019-04-04
    • 2012-02-18
    • 2017-03-05
    相关资源
    最近更新 更多