seventeen seventeen - 3 years ago 235
ActionScript Question

Actionscript 3: Identifying an array element to delete when the elements are objects/class instances

I have an array of objects, some of which are movieclips and some instances of classes. I need to remove an item from the array but are struggling with how best to identify which array index to delete.

I am currently using this code, which does work

var i:int;
for (i = 0; i < list.length; i++) {

if (list[i].toString() == '[object myClass]') {
trace('found', i);


I am thinking a better way must exist to get the object name and without looping through the array.

Answer Source

I could use a little clarification on how you want to identify the object(s) that should be removed. If you are looking to simply remove any object that is an instance of the myClass class, I would recommend the is keyword.

Also, a warning, removing items from a list as you are iterating over it is just asking for trouble. If you remove object at index [0] then the object that used to be at index [1] is now index [0], but your for loop is going to increment i by one at the end of each iteration, so you will never check index [0] again. Thus you may skip one or more of the objects that you wanted to remove.

Instead try iterating over it backwards-- that should resolve that problem.

Here is what both of those recommendations together looks like:

for (var i:int = (list.length - 1); i >= 0; i--)
    if (list[i] is myClass)
        trace("found", i);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download