当我们想要跳过任何循环的当前迭代时使用 continue 语句。当编译器看到 continue 语句时,将跳过 continue 之后的其余语句,并将控制权转移回循环中的第一条语句以进行下一次迭代。
它几乎用在所有编程语言中,我们通常会在条件代码块中遇到continue 语句。
continue;
让我们考虑一个例子,我们在 while 循环中使用 continue 语句。
考虑下面显示的例子 -
void main(){ var num = 10; while(num >= 3){ num--; if(num == 6){ print("Number became 6, so skipping."); continue; } print("The num is: ${num}"); } }
在上面的代码中,我们有一个名为 num 的变量,我们使用 while 循环进行迭代,直到数字大于或等于 3。然后,我们使用 if 语句维护一个条件检查,如果我们遇到一个条件, num 等于 6,我们继续。
输出结果
The num is: 9 The num is: 8 The num is: 7 Number became 6, so skipping. The num is: 5 The num is: 4 The num is: 3 The num is: 2
让我们考虑另一个使用 continue 语句的例子。
考虑下面显示的例子 -
void main(){ var name = "apple"; var fruits = ["mango","banana","litchi","apple","kiwi"]; for(var fruit in fruits){ if(fruit == name){ print("Don't need an apple!"); continue; } print("current fruit : ${fruit}"); } }输出结果
current fruit : mango current fruit : banana current fruit : litchi Don't need an apple! current fruit : kiwi