Ne peut pas sortir de boucles imbriquées pour
-
20-09-2019 - |
Question
J'ai la fonction suivante, mais malgré l'utilisation de l'instruction break, il ne semble pas être arrêter après qu'il trouve une correspondance dans le tableau:
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...")
}
}
}
}
La solution
Ahh ... Je vois.
Utilisé une étiquette, maintenant il fonctionne:
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...")
}
}
}
}
Autres conseils
Ajouter un var bool appelé trouvé initialisé à false.
Modifier vos conditions de boucle de
i < _playersList.length
à
i < _playersList.length && !found
puis avant votre pause, Obtenue = true
break
ne sortir une boucle (ou commutateur) à la fois.
Je pense qu'il ya une autre solution avec moins de code:
private function checkMatch():void {
for (var i : int = 0; i < _playerList.length-1; i++) {
if (_playerList.indexOf(_playerList[i], i+1) > i) {
break;
}
}
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow