部分摘抄自:http://www.nowamagic.net/javascript/js_JumpLoops.php
多重循环在编程中会经常遇到,那么在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
退出each循环不能用break,否则会报错。退出each循环应该用return false,如:
var clientName = $("#clientName").val();
$.each(avaiableTags,function(key,value){
if(value == clientName){return false;}
});