views:

170

answers:

3

I have the following function but despite using the break statement, it doesn't seem to be stopping after it finds a match in the array:

private function CheckMatch() {

// _playersList is the Array that is being looped through to find a match

            var i:int;
            var j:int;

            for (i= 0; i < _playersList.length; i++) {

                    for (j= i+1; j < _playersList.length; j++) {
                        if (_playersList[i] === _playersList[j]) {
                            trace("match:" + _playersList[i] + " at " + i + " is a match with "+_playersList[j] + " at " + j);

                            break;

                            } else {
                            // no match
                            trace("continuing...")

                            }
                        }
                    }

                }
+1  A: 

break will only break out one loop (or switch) at a time.

Autopulated
Oh, yeah, I guess the op could mean break out of both loops, in which case you're right about the problem.
Kaleb Pederson
A: 

Add a bool var called found initialized to false.

Change your loop conditions from

i < _playersList.length

to

i < _playersList.length && !found

then before your break, set found = true

Chad
+1  A: 

Ahh...I see.

Used a label, now it works:

private function CheckMatch() {

// _playersList is the Array that is being looped through to find a match

        var i:int;
        var j:int;

     OuterLoop:   for (i= 0; i < _playersList.length; i++) {

                for (j= i+1; j < _playersList.length; j++) {
                    if (_playersList[i] === _playersList[j]) {
                        trace("match:" + _playersList[i] + " at " + i + " is a match with "+_playersList[j] + " at " + j);

                        break OuterLoop;

                        } else {
                        // no match
                        trace("continuing...")

                        }
                    }
                }

            }
redconservatory