话说跳出循环如for for..in等,很多人想到的无非就是break、continue、return,而且return的跳出还必须借助函数这样的宿主环境才行,那么如果有多个for循环,我们该如何完全跳出呢?
接下来我们进行一些实验,这些实验都不是很复杂,也没有往深度的去解读,仅仅是一个普通的实验,如下:
let a = ['a','b','c'],
b = [1,2,3],
c = ['hello', 'world'];
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
for (let j = 0; j < b.length; j++) {
console.log(b[j]);
for (let m = 0; m < c.length; m++) {
console.log(c[m]);
};
};
};
执行后显示如下:
a
1
hello
world
2
hello
world
3
hello
world
b
1
hello
world
2
hello
world
3
hello
world
c
1
hello
world
2
hello
world
3
hello
world
这是一个正常的循环完整code,那么接下来进行相应的跳出实验。
首先我们尝试使用break,如下:
let a = ['a','b','c'],
b = [1,2,3],
c = ['hello', 'world'];
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
for (let j = 0; j < b.length; j++) {
if(j==1){
break;
}
console.log(b[j]);
for (let m = 0; m < c.length; m++) {
console.log(c[m]);
};
};
};
显示如下:
a
1
hello
world
b
1
hello
world
c
1
hello
world
通过上面的代码我们大致得出一个结论,break跳出的是当前整个循环,包括循环内部的所有后续要执行的代码均不再执行,但是不影响外部大的循环。
接下来实验第二种continue
let a = ['a','b','c'],
b = [1,2,3],
c = ['hello', 'world'];
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
for (let j = 0; j < b.length; j++) {
if(j==1){
continue;
}
console.log(b[j]);
for (let m = 0; m < c.length; m++) {
console.log(c[m]);
};
};
};
显示如下:
a
1
hello
world
3
hello
world
b
1
hello
world
3
hello
world
c
1
hello
world
3
hello
world
可以看出,continue是跳出当前循环,并开始下一次要执行的代码,所以它不会影响到下一个循环体内的循环。
对于return主要用于在函数内,这里就不举例了。
接下来思考一个问题,如何完全跳出多重循环。
这个问题我刚开始也很纠结,后来网上查了下资料,发现可以使用命名空间的方法,即可以给循环加名字,然后通过break加上循环名来跳转到某个循环或者直接跳处函数,如下:
let a = ['a','b','c'],
b = [1,2,3],
c = ['hello', 'world'];
firstName:
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
twoName:
for (let j = 0; j < b.length; j++) {
if(j==1){
continue;
}
console.log(b[j]);
threeName:
for (let m = 0; m < c.length; m++) {
if(m==1){
break twoName;
}
console.log(c[m]);
};
};
};
显示如下:
a
1
hello
b
1
hello
c
1
hello
通过上面的列子得出,这种命名空间的方法可以通过break加上空间名可以跳转到空间名所在作用域后继续执行该作用域的下一步代码。
写的很乱,不知道大家是否明白。
智言个人博客






评论前必须登录!
注册