javascript implements the label tag breaking out of the loop operation

  • 2021-01-22 04:53:51
  • OfStack

Appearance:

First, let's talk about why we need the label tag. We already know that there are break and continue that break out of the loop, but they can't help with multiple loops, so we have the label tag to work for us.

Let's first look at break alone


for(var i=0;i<4;i++){
  for(var j=0;j<4;j++){
    if(i===1&&j===1){
      break;
    }else{
      console.log("i:"+i+"--j:"+j);
    }
  }
}

Running results:


i:0--j:0
i:0--j:1
i:0--j:2
i:0--j:3
i:1--j:0
 when i and j===1 ", it just jumped out j So it's going to go back i The loop body 
i:2--j:0
i:2--j:1
i:2--j:2
i:2--j:3
i:3--j:0
i:3--j:1
i:3--j:2
i:3--j:3

From the above results, we can find that the simple use of break is far from being able to complete some complex operations.

label tags can be any name, but cannot be reserved words, they are almost identical to break; continue; Use together.


 bk:for(var i=0;i<4;i++){
   for(var j=0;j<4;j++){
     if(i===1&&j===1){
       break bk;
     }else{
       console.log("i:"+i+"--j:"+j);
     }
   }
 }

Running results:


1 i:0--j:0
2 i:0--j:1
3 i:0--j:2
4 i:0--j:3
5 i:1--j:0

Successfully break out of the loop.

bk is just a name, you are free, of course not a keyword in js

continue: continue: continue: continue: continue

It's a very simple example, and I hope it's helpful.


Related articles: