从数组中删除对象,然后删除

Remove an object from an array and then delete

本文关键字:删除 然后 对象 数组      更新时间:2023-09-26

我正在用MVC设计模式构建一个系统。我需要创建一系列控制器。稍后,当不再需要这些控制器时,我可能希望能够将它们从内存中删除。控制器是使用新关键字创建的,所以我遇到了如何存储对对象的引用的问题。我决定使用数组。当我创建时,它们被添加到数组中,当我销毁时,我会循环遍历数组并移除。我想确保我没有泄露记忆。假设我没有创建对控制器对象的其他引用,这将有效地使它们成为垃圾收集的候选者:

//creating the objects and storing them
//create image controller & modelfor each image (model injected as a dependency)
 for (var i = 0; i < imageData.galleryImages.length; i++) {
 imageControllerArray.push( new ImageController(someParam, new model()));
 };
//here I want to destroy the controllers
 while(imageControllerArray.length){
        imageControllerArray.pop(); //would this do it?
        //delete imageControllerArray.pop(); //What about this?
        // imageControllerArray.pop().destroy() //where each controller deletes itself
    }

解决这个问题的最佳方法是什么?有什么建议吗?我的想法是,我需要做的是删除对控制器的任何引用,而不是对象本身。我担心我的方法可能是在某个全局空间上创建对象,因此仅仅删除数组引用实际上不会释放对象进行垃圾收集。

如果您需要检查从数组中删除的对象,请从数组中捕获弹出的项,您将从数组中移除该项,现在可以应用您需要对其执行的任何其他操作,例如检查是否有其他对象指向弹出的数组项。

如果有任何东西指向从数组中删除的弹出项目,你可以打赌它将永远存在,直到指向弹出数组项目的项目被删除或删除。

  while(imageControllerArray.length){
     var myArrayItem = imageControllerArray.pop();
       if(myArrayItem.otherObj){
       delete myArrayItem.otherObj;
      //you're now good to go
};
  };
相关文章: