[转]JavaScript break跳出多重循环
多重循环在编程中会经常遇到,那么在JavaScript中如何指定跳出那层的循环呢。其实这也是break的一个用法,下面是一个不错的例子,来自《JavaScript权威指南》,可以参考下:
Code
<script type= "text/javascript" > outerloop: //命名外圈语句 for (i=0; i<10; i++) { innerloop: //命名内圈语句 for (j=0; j<10; j++) { // 跳出内圈循环 if (j>3){ break ;} // 跳出内圈循环 if (i==2){ break innerloop;} // 跳出外圈循环 if (i==4){ break outerloop;} document.write( "i = " +i+ " , j = " +j+ "<br />" ); } } document.write( "final" + " i = " +i+ " , j = " +j); </script> |
程序运行结果:
i = 0 , j = 0 i = 0 , j = 1 i = 0 , j = 2 i = 0 , j = 3 i = 1 , j = 0 i = 1 , j = 1 i = 1 , j = 2 i = 1 , j = 3 i = 3 , j = 0 i = 3 , j = 1 i = 3 , j = 2 i = 3 , j = 3 final i = 4 , j = 0 |