Home >Web Front-end >JS Tutorial >Javascript implements label label jumping out of loop operation_javascript skills

Javascript implements label label jumping out of loop operation_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:11:521466browse

Appearance:

First of all, let’s talk about why we need the label label. Although we already know that there are break and continue to jump out of the loop, but if there are multiple loops, they are powerless, so the label label appears to serve us.

Let’s first take a look at using 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);
    }
  }
}

Run result:

i:0--j:0
i:0--j:1
i:0--j:2
i:0--j:3
i:1--j:0
当i和j===1的时候,它只跳出了j循环,因此它又会回到i循环体
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 running results, we can find that simply using break is far from being able to complete some complex operations.

The label tag can be any name, but it cannot be a reserved word. They are almost used in conjunction with break; continue;.

 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);
     }
   }
 }

Run result:

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 jumped out of the loop.

Tips: bk is just a name, you can do whatever you want, of course it cannot be a keyword in js

The usage of continue is the same, no examples are given.

A very simple example, I hope it will be helpful to everyone’s learning.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn