Is using labels in JavaScript bad practice?

前端 未结 4 2005
遥遥无期
遥遥无期 2020-12-04 23:55

I just found out about using label s in JavaScript, such as:

for (var i in team) {
    if(i === \"something\") {
        break doThis: //Goto the label
    }         


        
4条回答
  •  醉话见心
    2020-12-05 00:25

    The labels in JavaScript are used mainly with break, or continue in nested loops to be able to break the outer, or continue the outer loop from the code inside inner loop:

        outer:
        for (let i = 0; i < 10; i++)
        { 
           let k = 5;
           for (let j = 0; j < 10; j++) // inner loop
              if (j > 5) 
                   break; // inner 
              else
                   continue outer;  // it will go to next iteration of outer loop
        }
    

    If you used continue without 'outer' label, it would go to the next iteration of inner loop. That's why there is a need for labels in Javascript.

提交回复
热议问题