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

                            }
                        }
                    }

                }
4

4 回答 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...")

                        }
                    }
                }

            }
于 2010-01-12T17:03:59.373 回答
2

添加一个名为 found 的 bool var,初始化为 false。

改变你的循环条件

i < _playersList.length

i < _playersList.length && !found

然后在你休息之前,设置 found = true

于 2010-01-12T17:00:33.963 回答
1

break一次只会中断一个循环(或切换)。

于 2010-01-12T16:58:23.233 回答
0

我认为还有另一种代码更少的解决方案:

private function checkMatch():void {
    for (var i : int = 0; i < _playerList.length-1; i++) {
        if (_playerList.indexOf(_playerList[i], i+1) > i) {
            break;
        }
    }
}
于 2013-01-02T10:45:31.077 回答