continue
- continue 为结束当前循环的当次循环,继续执行当前循环的下次循环;结束的是一次。
let arr = [1,2,3,4,5];
for (let index = 0; index < arr.length; index++) {
console.log('---------');
for(let j=0; j<arr.length; j++) {
if(arr[j] % 4 === 0) {
continue;
}
console.log('++++++++', arr[j]);
}
console.log('===========');
}
/**
---------
++++++++ 1
++++++++ 2
++++++++ 3
++++++++ 5
===========
---------
++++++++ 1
++++++++ 2
++++++++ 3
++++++++ 5
===========
---------
++++++++ 1
++++++++ 2
++++++++ 3
++++++++ 5
===========
---------
++++++++ 1
++++++++ 2
++++++++ 3
++++++++ 5
===========
---------
++++++++ 1
++++++++ 2
++++++++ 3
++++++++ 5
===========
*/
break
- break 是结束当前所在的循环。如果有多层循环,结束的是所在层的那个循环,不会终止所有循环。
let arr = [1,2,3,4,5];
for (let index = 0; index < arr.length; index++) {
console.log('---------');
for(let j=0; j<arr.length; j++) {
if(arr[j] % 4 === 0) {
break;
}
console.log('++++++++', arr[j]);
}
console.log('===========');
}
/**
---------
++++++++ 1
++++++++ 2
++++++++ 3
===========
---------
++++++++ 1
++++++++ 2
++++++++ 3
===========
---------
++++++++ 1
++++++++ 2
++++++++ 3
===========
---------
++++++++ 1
++++++++ 2
++++++++ 3
===========
---------
++++++++ 1
++++++++ 2
++++++++ 3
===========
*/
总结
- continue 是结束当次循环,继续执行下次循环;
- break 是结束当层循环,继续执行后面的语句;
- return 会结束所有循环,函数中return后面的所有语句都不会执行。