如何跳转到下一个顶级循环? [英] How to jump to next top level loop?

查看:59
本文介绍了如何跳转到下一个顶级循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 for 循环嵌套在另一个 for 循环中.我怎样才能做到在内循环中发生某些事情时,我们退出并跳转到外循环的下一次迭代?

I have a for loop nested in another for loop. How can I make it so that when somethign happens in the inner loop, we exit and jump to the next iteration of the outer loop?

uuu <- 0

for (i in 1:100) {
    uuu <- uuu + 1
    j <- 1000
    for (eee in 1:30) {
        j <- j - 1
        if (j < 990) {
            # if j is smaller than 990 I hope start next time of i
        }
    }
}

推荐答案

@flodel 对此有正确的答案,即使用 break 而不是 next.不幸的是,无论使用哪种控制流构造,该答案中的示例都会给出相同的结果.

@flodel has the correct answer for this, which is to use break rather than next. Unfortunately, the example in that answer would give the same result whichever control flow construct was used.

我添加以下示例只是为了说明这两种结构的行为有何不同.

I'm adding the following example just to make clear how the behavior of the two constructs differs.

## Using `break`
for (i in 1:3) {
   for (j in 3:1) {     ## j is iterated in descending order
      if ((i+j) > 4) {
         break          ## << Only line that differs
      } else {
         cat(sprintf("i=%d, j=%d\n", i, j))
      }}}
# i=1, j=3
# i=1, j=2
# i=1, j=1

## Using `next`
for (i in 1:3) {
   for (j in 3:1) {     ## j is iterated in descending order
      if ((i+j) > 4) {
         next           ## << Only line that differs
      } else {
         cat(sprintf("i=%d, j=%d\n", i, j))
      }}}
# i=1, j=3
# i=1, j=2
# i=1, j=1
# i=2, j=2   ##  << Here is where the results differ
# i=2, j=1   ##
# i=3, j=1   ##

这篇关于如何跳转到下一个顶级循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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