How to jump to next top level loop?

后端 未结 2 1168
滥情空心
滥情空心 2021-02-19 02:13

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 iteratio

2条回答
  •  -上瘾入骨i
    2021-02-19 02:41

    @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   ##
    

提交回复
热议问题