The label statement in JavaScript, and the application

Source: Internet
Author: User

Label statement: You can add tags to your code for future use.

Syntax: label:statement

Example:

Start:    for (var i=0;i<10;i++) {    console.log (i);  };

Example extensions:

Start:    for (var i=0;i<10;i++) {    console.log (i);      for (var j=0;j<5;j++) {      console.log (' J ' +j);       if (i>5) {        // break ;      Only the last loop is terminated, and the last loop does not terminate the break         start;      // all terminated.       }    }  };

Application Scenarios:

varItemsid = [1,3];varall = [[{Id:1,name:hehe},{id:3,name:hehe}],[{id:2,name:hehe},{id:4, Name:hehe}]];//we have the top two arrays, ITEMSID is the ID array, all is a two-dimensional array, where the elements are, according to the parity of the ID placed, the object of the item. Now we want to find the object corresponding to the ID in each items, this time we need multiple loops to find: for(vari=0;i<itemsid.length;i++){     for(varj=0;j<all.length;j++){         for(vark=0;k<all[j].length;k++){            if(All[j][k].id = =Itemsid[i])                {Console.log (all[j][k]);  Break; }        }    }}//At this point we will find that when we find the right object, using break can only jump out of the inner K Loop, and the J Loop will go on. There are a lot of unnecessary loops. We hope that, when found, jump directly outside the J Loop and start looking for the next ID. At this point, we need to use the label. The code is as follows: for(vari=0;i<itemsid.length;i++) {outpoint: for(varj=0;j<all.length;j++){         for(vark=0;k<all[j].length;k++){            if(All[j][k].id = =Itemsid[i])                {Console.log (all[j][k]);  BreakOutpoint; }        }    }}//in this way, when all[j][k].id = = Itemsid[i], you will jump out of the outpoint position, jump out of two loops, starting from the next ID to find. Many times less cycles. 

The label statement in JavaScript, and the application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.