0

I have the following code. In the onClientClose method I want to remove the _socketServicer instance from the _clientSockets array if it is closed. How do I reference the _socketServicer instance in the array if I don't know its index?

public function connectHandler(event:ServerSocketConnectEvent):void {                            _socketServicer=new SocketService(event.socket, this,log);
            _socketServicer.addEventListener(Event.CLOSE, onClientClose);
            _clientSockets.push(_socketServicer); //maintain a reference to prevent premature garbage collection
        }

        private function onClientClose(event:Event):void {
            //Nullify references to closed sockets
            for each (var servicer:SocketService in _clientSockets) {
                if (servicer.closed)
                    servicer=null;
            }
        }

1 Answer 1

2

You can use .indexOf():

clientSockets[ clientSockets.indexOf(servicer) ];
Sign up to request clarification or add additional context in comments.

2 Comments

thanks yes, discovered the indexOf method which can use to grab the index then use splice to remove if needed
if you are looking to remove items from the array it would be best to not use the for each loop but instead use the for loop where "i" is already known. If you will be possibly deleting multiple elements from the array then a decrementing for loop would be best. So to wrap it up the type of loop you use is defined by the logic that you will be applying inside of it.

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.