无法跳出嵌套的 for 循环
我有以下函数,但尽管使用了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...")
}
}
}
}
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...")
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
啊……我明白了。
使用了标签,现在可以使用了:
Ahh...I see.
Used a label, now it works:
添加一个名为 find 的 bool var,初始化为 false。
将循环条件从 更改为
then ,设置 find = true
在中断之前
Add a bool var called found initialized to false.
Change your loop conditions from
to
then before your break, set found = true
break
一次只会中断一个循环(或开关)。break
will only break out one loop (or switch) at a time.我认为还有另一种代码更少的解决方案:
I think there another solution with less code: