JS understanding of the break, continue, and return three keywords

meaning

Statement description
break Exit switch statement or loop
continue Skip the current iteration in the cycle, and the cycle continues in the next iteration
return Exit function and return value of the function

break statement

break statement is used to exit the switch statement or loop, such as for, for ... in, for ... of, while, do ... while.

  1. When the break statement for a switch statement, the code block out switch, code execution is halted.

For chestnut:

	var num=prompt("请输入一个数");
	switch (num%2){
	    case 0:console.log("这个数是偶数");break;
	    case 1:console.log("这个数是奇数");break;
	}

Results obtained input 4:

	这个数是偶数
  1. When the break statement is used to loop, the loop will terminate execution and implementation of the loop code (if any).

chestnut:

    for(var i=1;i<10;i++){
        if(i==5) break;
        console.log(i);
    }
    console.log("循环结束");

result:

	1
	2
	3
	4
	循环结束
  1. Label for optional break statement reference code block for the jump.

Summary: General break statement can only be used in the loop or switch.

continue Statement

continue iteration for skipping a cycle, and continue to the next iteration loop.

However, at the time of execution continue statement, showing two different types of cycles:

  1. In the while loop, will first determination condition, if the condition is true, the loop performed once again.

chestnut:

	var i=1;
	while (i<5){
	    i++;
	    if (i==4) continue;
		console.log(i);
	}
	console.log("循环结束");

result:

	1
	2
	3
	5
	循环结束
  1. In a for loop, self-growth expression (such as: i ++) will first calculated, and then determine whether a condition is true, then decide whether to perform iterative.

chestnut:

    for(var i=1;i<4;i++){
        if(i==3) continue;
        console.log(i);
    }
    console.log("循环结束");

result:

	1
	2
	4
	循环结束
  1. continue statement can be used in an optional label references.

Summary: General continue statement can only be used in the loop or switch.

return statement

The return statement terminates execution of the function and the function's return value.

The return statement can only be used in vivo function, resulting in a syntax error occurs at any other place will!

	function fn(a,b){
		return a+b;
		console.log(a*b);
		}
	console.log(fn(1,2));

result:

	3

to sum up

  1. break out of the switch or for loop statement; Continue iteration for a skip cycle and continue to the next iteration cycle; return for performing the function and terminating the function return value.
  2. break the end the entire loop body; Continue ending a single cycle; return is the end of the entire function.
发布了59 篇原创文章 · 获赞 78 · 访问量 2万+

Guess you like

Origin blog.csdn.net/PrisonersDilemma/article/details/89487334