Question about loops and continue

后端 未结 4 2083
轮回少年
轮回少年 2021-01-06 10:12

So is this actually naming the loop to nextLoop? So when it says continue nextLoop, does it go back to the top right away?

   var t         


        
4条回答
  •  悲&欢浪女
    2021-01-06 10:57

    Yes. This is useful for when you have a loop nested inside another loop and you want to continue the outer loop. Here's a page on MDC about it. So in your case, during the i = 2 loop if, from within the j loop, you say continue nextLoop, it'll jump out of the j loop, do the i increment, and continue with i = 3.

    Using continue with labels is not usually good practice; it can indicate that the logic needs to be refactored. But it's perfectly valid syntactically and I expect someone will chime in with an example situation where they feel it's absolutely necessary.

    Edit Answering your edit, the label (name) of the loop is nextLoop (without the colon): You can label statements and then use those labels as the targets of continue and break. Check out the spec for details. The typical use is to label loops as in your example and either continue or break them, but note that break also applies to nested switch statements -- you can label them like loops and break to an outer one from within one of the inner one's cases. You can even intermix them so you can break a loop from within a switch (the label namespace is common to both).

提交回复
热议问题