return
return只能出现在函数体中,单独出现在其他任何地方都是非法的,会抛出错误:
Uncaught SyntaxError: Illegal return statement
如果return出现在函数内部的for循环中,则会终止当前for循环及return语句之后的函数代码,比如这段代码
function returnInLoop() {
for(let i = 0; i < 5; i++) {
if(i === 1) {
return 2333;
}
console.log(i);
}
console.log('loop end');
}
returnInLoop();
// 打印结果
0
2333
continue
continue只能出现在for、while、do/while中,出现在其他地方都是非法的,会抛出错误Uncaught SyntaxError: Illegal continue statement: no surrounding iteration statement
如果在一个迭代语句中使用continue,那么会跳过本次迭代,不会执行continue下面的迭代代码。不影响迭代之外的代码执行。
function continueInLoop() {
for(let i = 0; i < 5; i++) {
if(i === 1) {
continue;
}
console.log(i);
}
console.log('loop end');
}
continueInLoop();
// 打印结果
0
2
3
4
loop end
特别注意,如果在while语句中使用continue,很容易造成死循环,而for循环一般不会
function continueInLoop() {
let i = 0
while (i < 5) {
if (i === 1) {
// 这行代码会造成死循环
continue;
}
console.log(i)
// 可以把自增语句放到顶部解决
i++;
}
console.log('loop end')
}
continueInLoop()
// 打印结果
0
break
break语句只能出现在for、while、do/while、switch语句中,出现在其他地方会抛出错误
Uncaught SyntaxError: Illegal break statement
如果在一个迭代语句中使用break,那么会终止整个迭代,不会执行迭代代码内部break下面的代码,不影响迭代之外的代码执行。
function breakInLoop() {
for (let i = 0; i < 5; i++) {
if (i === 1) {
break;
}
console.log(i)
}
console.log('loop end')
}
breakInLoop()
// 打印结果
0
loop end
// 在switch语句中,如果遇到break则跳出switch执行switch下面的代码
switch (fruitName) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
break;
case 'Apples':
console.log('Apples are $0.32 a pound.');
// 如果这个break被省略,则无论fruit是否为Apples都会执行这个case代码块,知道遇到break或者switch结束才会停止
case 'Bananas':
console.log('Bananas are $0.48 a pound.');
break;
default:
// 一旦有任何一个case出现了break,都不会进入default
console.log('Sorry, we are out of ' + fruitName + '.');
}
// switch语句中如果不加break可能会产生意想不到的bug
const foo = 0;
switch (foo) {
case -1:
console.log('negative 1');
break;
case 0: // foo 的值为 0 所以匹配这里所以这一块会运行
console.log(0);
// 注意:那个没写的 break 原本在这儿
case 1: // 'case 0:' 里没有 break 语句所以这个 case 也会运行
console.log(1);
// 遇到了 break,所以不会再继续进入 'case 2:' 了
case 2:
console.log(2);
// break;
default:
console.log('default');
}
// 0
// 1
// 2
// default
forEach中不能使用continue和break!也无法跳过或终止循环