语句
- Try…Catch语句 。语句中包含1-多个Try语句,0-多个Catch语句。如果Try语句或者调用的方法抛出异常,会执行到Catch语句。如果没有抛出异常,Catch语句就会被跳过。 Try-Catch语句可以进行嵌套。
try { throw "myException" // generates an exception}catch (e) {// statements to handle any exceptions logMyErrors(e) // pass exception object to error handler}
- Finally语句。Finally语句包含在 Try和 Catch语句完成后,在Try…Catch语句之前的部分,无论是否抛出异常, Finally语句都会执行。返回的值不管 Try和 Catch返回了什么,返回的是 Try-Catch-Finally的值。 Finally覆盖返回值也适用于 Try-Catch语句。
function f() {try { console.log(0); throw "bogus";} catch(e) { console.log(1); return true; // this return statement is suspended // until finally block has completed console.log(2); // not reachable} finally { console.log(3); return false; // overwrites the previous "return" console.log(4); // not reachable}// "return false" is executed now console.log(5); // not reachable}f(); // console 0, 1, 3; returns false
- Label语句。用 Label标识一个循环,之后用 Break/Continue来指出循环的终止。语句:Label:Statement Label的值是任意非保留字的 JS标识符, Statement是任意你想得到的语句。
var num = 0; for (var i = 0 ; i < 10 ; i++){ for (var j = 0 ; j < 10 ; j++){ if( i == 5 && j == 5 ){ break; } num++; } } alert(num); // 循环在 i 为5,j 为5的时候跳出 j循环,但会继续执行 i 循环,输出 95对比使用了 Label 之后的程序:(添加 Label 后)var num = 0; outPoint: for (var i = 0 ; i < 10 ; i++){ for (var j = 0 ; j < 10 ; j++){ if( i == 5 && j == 5 ){ break outPoint; } num++; } } alert(num); // 循环在 i 为5,j 为5的时候跳出双循环,返回到outPoint层继续执行,输出 55对比使用了break、continue语句:var num = 0; outPoint: for(var i = 0; i < 10; i++) { for(var j = 0; j < 10; j++) { if(i == 5 && j == 5) { continue outPoint; } num++; } } alert(num); //95
- Break语句。语法第一个是终止当前的语法或者 Switch,第二种是终止指定的 Label语句。
var x = 0;var z = 0labelCancelLoops: while (true) { console.log("外部循环: " + x); x += 1; z = 1; while (true) { console.log("内部循环: " + z); z += 1; if (z === 10 && x === 10) { break labelCancelLoops; } else if (z === 10) { break; } }}
- Continue语句。除了继续执行的含义,还有一种:当一个含有 Checkiandj语句碰到 一个标签为Checkj语句,如果碰到 Continue语句,会终止 Checkj迭代进行下一轮迭代。每次碰到 Continue语句,Checkj语句是一直重复执行直到条件为 False。当返回 False后,Checkiandj语句会一直重复执行直到条件为 False。返回False后再执行下面的语句。 如果 Continue语句中有一个标记Checkiandj,程序将会从 Checkiandj 语句块的顶部继续执行。

- RangeError: Maximum call stack size exceeded 错误原因:由于最后的factorial()括号内一直未填入具体的数值,导致循环一直存在,一直循环到超过最大调用堆栈而报错。 当()写入具体数值,比如3,会执行到结果为6.
var factorial=function fac(n) { return n<2?1:n * fac(n-1);};console.log(factorial());//为啥factorial()会出现一个1,9个3?