关于循环和继续的问题 [英] Question about loops and continue

查看:67
本文介绍了关于循环和继续的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上是将循环命名为 nextLoop 吗?所以当它说继续nextLoop 时,它会立即回到顶部吗?

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 total = 0;
        nextLoop:
        for ( var i = 0; i < 7; ++i ) {
            for ( var j = 0; j < 6 ; ++j ) {
                if ( i < 5 )
                continue nextLoop;
                total++;
                }
            total++;
        }
    total++;
    document.write( total );

修改:

是否将循环命名为 nextLoop:?如果是这样,你能说出什么呢?任何对命名原因的引用都有用吗?

Is that naming the loop nextLoop:? If so, what else can you name? Any references to why naming stuff can be useful?

推荐答案

是的。当您将循环嵌套在另一个循环中并且希望继续外部循环时,这非常有用。 这是关于MDC的页面。所以在你的情况下,在 i = 2 循环期间,如果在 j 循环中,你说继续nextLoop ,它会跳出 j 循环,执行 i 增量,并继续 i = 3

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.

编辑回答你的编辑,循环的标签(名称)是 nextLoop (没有冒号):您可以标记语句,然后使用这些标签作为的目标<继续中断。有关详细信息,请查看规范。典型的用法是在示例中标记循环, continue break ,但请注意 break 也适用于嵌套的开关语句 - 你可以将它们标记为循环并从内部一个中断到外部一个人的情况。你甚至可以混合使用它们,这样你就可以在交换机中打破一个循环(标签命名空间对于两者都是通用的)。

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).

这篇关于关于循环和继续的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆