2

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);
                            list.removeAt(i);
                        }

                    }

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

1
  • 1
    If you can change from an array to a Dictionary, you can reduce your searching code to one step instead of looping over the array like you're doing. That will require some changes to the code that populates the array, of course. Depending on your requirements, that may or may not be practial. Commented Dec 11, 2017 at 21:00

1 Answer 1

3

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);
        list.removeAt(i);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Good answer. @seventeen, also, if you are removing the item from the display list, do so before you remove the item from the array. You could also just iterate through the display list itself (getChildAt(i)) and forgo the list array.
Thanks everyone, that exactly what I needed.
PS, I only have one instance of each class so looking up the item by class name is great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.