1. 程式人生 > >js跳出多重迴圈及$.each跳出多重迴圈

js跳出多重迴圈及$.each跳出多重迴圈

多重迴圈在程式設計中會經常遇到,那麼在JavaScript中如何指定跳出那層的迴圈呢。其實這也是break的一個用法,下面是一個不錯的例子,來自《JavaScript權威指南》,可以參考下:

Code

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <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>

程式執行結果:

1 2 3 4 5 6 7 8 9 10 11 12 13 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;}
});