无法跳出嵌套的for循环

3
我有下面这个函数,尽管使用了break语句,但它似乎在找到数组中的匹配项后并没有停止:
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...")

                            }
                        }
                    }

                }

你的意思是“似乎没有停止”吗?它是否输出了匹配?您是否使用调试器进行了检查? - Kaleb Pederson
我的意思是,根据跟踪语句,我仍然看到在早期的跟踪显示匹配后“继续”。 - redconservatory
4个回答

11

啊哈...我明白了。

使用了一个标签,现在它起作用了:

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

                        }
                    }
                }

            }

2

添加一个名为found的布尔变量,将其初始化为false。

将循环条件从

i < _playersList.length

为了

i < _playersList.length && !found

在休息之前,将found设置为true。


这个答案值得采纳 - 对我来说看起来更加简洁。 - mika

1

break只会中断一个循环(或者switch)。


哦,是的,我猜操作可能意味着跳出两个循环,这种情况下你关于问题是正确的。 - Kaleb Pederson

0
我觉得还有另一种更简洁的解决方案:
private function checkMatch():void {
    for (var i : int = 0; i < _playerList.length-1; i++) {
        if (_playerList.indexOf(_playerList[i], i+1) > i) {
            break;
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接