简体   繁体   English

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

[英]Remove an object from an array and then delete

I am building a system in the MVC design pattern. 我正在以MVC设计模式构建系统。 I need to create a series of controllers. 我需要创建一系列控制器。 Later I may want to be able to remove these controllers from memory when they are no longer needed. 稍后,当不再需要这些控制器时,我可能希望能够从内存中删除它们。 The controller is created using the new keyword so I had the problem of how to store references to the objects. 控制器是使用new关键字创建的,因此我遇到了如何存储对对象的引用的问题。 I decided to use an array. 我决定使用数组。 When I create they are added to an array, when I destroy I loop through the array and remove. 当我创建它们时,它们被添加到数组中,当我销毁它们时,我遍历该数组并删除。 I want to make sure that I am not leaking memory. 我想确保我没有泄漏内存。 Assuming I am not creating other references to the controller objects would this effectively make them candidates for garbage collection: 假设我没有创建对控制器对象的其他引用,这将有效地使它们成为垃圾收集的候选对象:

//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
    }

What is the best way to approach this problem? 解决此问题的最佳方法是什么? Any advice? 有什么建议吗? I get the idea that what I need to do is delete any references to the controllers rather than the objects themselves. 我的想法是,我需要做的是删除对控制器的所有引用,而不是对象本身。 I am concerned that my approach may be creating the objects on some global space and so just deleting the array reference won't actually free the object up for garbage collection. 我担心我的方法可能是在某个全局空间上创建对象,因此仅删除数组引用实际上不会释放该对象用于垃圾回收。

If you need to check the object being removed from the array catch the popped item from the array and you'll have removed the item from the array and now can apply whatever else it is that you need to do with it, like checking to see if any other object points to the popped array item. 如果您需要检查要从数组中删除的对象,请从数组中捕获弹出的项目,然后将其从数组中删除,然后可以应用您需要做的其他任何事情,例如查看如果任何其他对象指向弹出的数组项。

If anything points to the popped item being removed from the array you can bet it will live forever, until the item pointing to the popped array item is deleted or removed. 如果有什么东西指向要从阵列中删除的弹出项目,则可以打赌它会永远存在,直到指向弹出数组的项目被删除或删除为止。

  while(imageControllerArray.length){

     var myArrayItem = imageControllerArray.pop();

       if(myArrayItem.otherObj){

       delete myArrayItem.otherObj;

      //you're now good to go
};
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM