📜  Dart编程-循环

📅  最后修改于: 2020-11-05 04:15:27             🧑  作者: Mango


有时,某些指令需要重复执行。循环是执行此操作的理想方法。循环代表一组必须重复的指令。在循环的上下文中,重复称为迭代

下图说明了循环的分类-

循环分类

让我们从确定循环开始讨论。迭代次数是确定/固定的循环称为确定循环

Sr.No Loop & Description
1 for loop

The for loop is an implementation of a definite loop. The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array

2 for…in Loop

The for…in loop is used to loop through an object’s properties.

继续,让我们现在讨论不确定循环。当循环中的迭代次数不确定或未知时,将使用不确定循环。无限循环可以使用-

Sr.No Loop & Description
1 while Loop

The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed.

2 do…while Loop

The do…while loop is similar to the while loop except that the do…while loop doesn’t evaluate the condition for the first time the loop executes.

现在让我们继续讨论Dart的循环控制语句

Sr.No Control Statement & Description
1 break Statement

The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Following is an example of the break statement.

2 continue Statement

The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop.

使用标签控制流程

标签只是标识符,后跟一个冒号(:),该冒号应用于语句或代码块。标签可以与休息使用,并继续更精确地控制流量。

“ continue”“ break”语句及其标签名称之间不允许换行。同样,在标签名称和关联的循环之间不应有任何其他语句。

示例:带有中断的标签

void main() { 
   outerloop: // This is the label name 
   
   for (var i = 0; i < 5; i++) { 
      print("Innerloop: ${i}"); 
      innerloop: 
      
      for (var j = 0; j < 5; j++) { 
         if (j > 3 ) break ; 
         
         // Quit the innermost loop 
         if (i == 2) break innerloop; 
         
         // Do the same thing 
         if (i == 4) break outerloop; 
         
         // Quit the outer loop 
         print("Innerloop: ${j}"); 
      } 
   } 
}

成功执行上述代码后,将显示以下输出

Innerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Innerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Innerloop: 2
Innerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Innerloop: 4

示例:带有继续的标签

void main() { 
   outerloop: // This is the label name 
   
   for (var i = 0; i < 3; i++) { 
      print("Outerloop:${i}"); 
      
      for (var j = 0; j < 5; j++) { 
         if (j == 3){ 
            continue outerloop; 
         } 
         print("Innerloop:${j}"); 
      } 
   } 
}

成功执行上述代码后,将显示以下输出。

Outerloop: 0 
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 

Outerloop: 1 
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 

Outerloop: 2 
Innerloop: 0 
Innerloop: 1 
Innerloop: 2