0

i have a code

loop1:
    for(j=0;j<players.x.length;j++){
      //someting
loop2:
      for(k=0;k<tankmain[players.type[j]].tankbottom.size.length;k++){
        //someting else
loop3:
        for(i=0;i<darts.x.length;i++){  
          if(hit){
           //something
             break loop1;
             break loop2;
             break loop3;
    }
              
            }}}

    

but no matter how I position it the last two break loop gray out making the other 2 loops still run

magic gum
  • 49
  • 9

2 Answers2

1

You can use a label:

// Mark this loop, name it "outerLoop";
outerLoop: while (1) {
    while(1) {
        while(1) {
             if (condition) {
                 // break out of the specific loop "outerLoop". Works with continue too
                 break outerLoop;
             }
        }
    }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label for more info

mousetail
  • 7,009
  • 4
  • 25
  • 45
1

You are putting three breaks behind each other. But when hitting the first break in your loop you are already leaving the loop, therefore the other two won't be called. See the example below for one possible solution.

let loop1 = [1,2,3,4,5,6,7,8];
let loop2 = [10,11,12,13,14,15];
let loop3 = [50,51,52,53,54,55];

let breakLoop1 = false;
let breakLoop2 = false;
let hit = false;

for(j = 0; j < loop1.length; j++){
    console.log(`${j} from loop1`);
        //someting
        for(k = 0; k < loop2.length; k++){
            console.log(`${k} from loop2`);
            //someting else
            for(i = 0; i < loop3.length; i++){  
                console.log(`${i} from loop3`);
        
                if(i == 2) hit = true;

                    if(hit) {
                        //something
                        breakLoop1 = true;
                        breakLoop2 = true;
                        console.log("leaving loop 3");
                        break; //break loop3
                    } 
            }
            
            //break inside loop2
            if(breakLoop2) {
                console.log("leaving loop 2");
                break;  
            }
        }
        
        //break inside loop1
        if(breakLoop1) {
            console.log("leaving loop 1");
            break;  
        }
}
nosTa
  • 607
  • 6
  • 16