开发者

Can't break out of nested for loops

开发者 https://www.devze.com 2022-12-16 17:32 出处:网络
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:

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

                            }
                        }
                    }

                }


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

                        }
                    }
                }

            }


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;
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消