语句

  • Try…Catch语句 。语句中包含1-多个Try语句,0-多个Catch语句。如果Try语句或者调用的方法抛出异常,会执行到Catch语句。如果没有抛出异常,Catch语句就会被跳过。 Try-Catch语句可以进行嵌套。
  1. try {
  2. throw "myException" // generates an exception
  3. }
  4. catch (e) {
  5. // statements to handle any exceptions
  6. logMyErrors(e) // pass exception object to error handler
  7. }
  • Finally语句。Finally语句包含在 Try和 Catch语句完成后,在Try…Catch语句之前的部分,无论是否抛出异常, Finally语句都会执行。返回的值不管 Try和 Catch返回了什么,返回的是 Try-Catch-Finally的值。 Finally覆盖返回值也适用于 Try-Catch语句。
    1. function f() {
    2. try {
    3. console.log(0);
    4. throw "bogus";
    5. } catch(e) {
    6. console.log(1);
    7. return true; // this return statement is suspended
    8. // until finally block has completed
    9. console.log(2); // not reachable
    10. } finally {
    11. console.log(3);
    12. return false; // overwrites the previous "return"
    13. console.log(4); // not reachable
    14. }
    15. // "return false" is executed now
    16. console.log(5); // not reachable
    17. }
    18. f(); // console 0, 1, 3; returns false
  • Label语句。用 Label标识一个循环,之后用 Break/Continue来指出循环的终止。语句:Label:Statement Label的值是任意非保留字的 JS标识符, Statement是任意你想得到的语句。
  1. var num = 0;
  2. for (var i = 0 ; i < 10 ; i++){
  3. for (var j = 0 ; j < 10 ; j++){
  4. if( i == 5 && j == 5 ){
  5. break;
  6. }
  7. num++;
  8. }
  9. }
  10. alert(num); // 循环在 i 为5,j 为5的时候跳出 j循环,但会继续执行 i 循环,输出 95
  11. 对比使用了 Label 之后的程序:(添加 Label 后)
  12. var num = 0;
  13. outPoint:
  14. for (var i = 0 ; i < 10 ; i++){
  15. for (var j = 0 ; j < 10 ; j++){
  16. if( i == 5 && j == 5 ){
  17. break outPoint;
  18. }
  19. num++;
  20. }
  21. }
  22. alert(num); // 循环在 i 为5,j 为5的时候跳出双循环,返回到outPoint层继续执行,输出 55
  23. 对比使用了breakcontinue语句:
  24. var num = 0;
  25.   outPoint:
  26.   for(var i = 0; i < 10; i++)
  27.   {
  28.   for(var j = 0; j < 10; j++)
  29.   {
  30.   if(i == 5 && j == 5)
  31.   {
  32.   continue outPoint;
  33.    }
  34.    num++;
  35.   }
  36.   }
  37.   alert(num); //95
  • Break语句。语法第一个是终止当前的语法或者 Switch,第二种是终止指定的 Label语句。
  1. var x = 0;
  2. var z = 0
  3. labelCancelLoops: while (true) {
  4. console.log("外部循环: " + x);
  5. x += 1;
  6. z = 1;
  7. while (true) {
  8. console.log("内部循环: " + z);
  9. z += 1;
  10. if (z === 10 && x === 10) {
  11. break labelCancelLoops;
  12. } else if (z === 10) {
  13. break;
  14. }
  15. }
  16. }
  • Continue语句。除了继续执行的含义,还有一种:当一个含有 Checkiandj语句碰到 一个标签为Checkj语句,如果碰到 Continue语句,会终止 Checkj迭代进行下一轮迭代。每次碰到 Continue语句,Checkj语句是一直重复执行直到条件为 False。当返回 False后,Checkiandj语句会一直重复执行直到条件为 False。返回False后再执行下面的语句。 如果 Continue语句中有一个标记Checkiandj,程序将会从 Checkiandj 语句块的顶部继续执行。image.png
  • RangeError: Maximum call stack size exceeded 错误原因:由于最后的factorial()括号内一直未填入具体的数值,导致循环一直存在,一直循环到超过最大调用堆栈而报错。 当()写入具体数值,比如3,会执行到结果为6.
  1. var factorial=function fac(n)
  2. {
  3. return n<2?1:n * fac(n-1);
  4. };
  5. console.log(factorial());//为啥factorial()会出现一个1,9个3?