和continue语句一样,在循环语句中与条件语句一起使用。 break语句用于跳出本层循环体,开始执行本层循环体外的代码。
- for(var i=1;i<=10;i++)
- {
- if(i==6) break;
- document.write(i);
- }
- //输出结果:12345
break语句跳出包含它的switch,while,do,for,或foreach语句。假如break不是在switch,while,do,for或者foreach语句的块中,将会发生编译错误。 当有switch,while,do,for或foreach语句相互嵌套的时候,break语句只是跳出直接包含的那个语句块。如果要在多处嵌套语句中完成转移,必须使用goto语句。
using System;
class Program { static void Main(string[] args) { int i = 0; int [] intArray = { 1,2,3,4,5,6,7,8,9,10}; //用while循环检索数组元素 while (i < intArray.Length) { if (i == 1) //数组索引为1时 { i++; continue;//结束本次循环,开始下一个循环 } else if (i == 5)//数组索引为5时,跳出循环体 { break; } Console.WriteLine(intArray[i]); i++; } Console.ReadKey(); } }