Question

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...")

                            }
                        }
                    }

                }
Was it helpful?

Solution

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...")

                        }
                    }
                }

            }

OTHER TIPS

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

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

I think there another solution with less code:

private function checkMatch():void {
    for (var i : int = 0; i < _playerList.length-1; i++) {
        if (_playerList.indexOf(_playerList[i], i+1) > i) {
            break;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top