一些有意思的javascript代码示例 记录更新

1 . 标签语句和continue

var i, j;

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i == 1 && j == 1) {
         continue loop1;
      } else {
         console.log("i = " + i + ", j = " + j);
      }
   }
}

// Output is:
//   "i = 0, j = 0"
//   "i = 0, j = 1"
//   "i = 0, j = 2"
//   "i = 1, j = 0"
//   "i = 2, j = 0"
//   "i = 2, j = 1"
//   "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"

loop2 放在 loop1 里面,当满足i ==1 和 j ==1的时候,循环会立即跳出loop2 并开始执行loop1 , 所以i =1,j=1 和i =1,j=2 都被掠过了

 

 

2 .使用try ,finally 做一个循环增加

var i =0,total = 0;
while(i<a.length){
    try{
        if((typeof a[i] != "number") || isNaN(a[i]))
            continue
        total += a[i]
    }
    finally{
        i++
    }
}

先try一下数组里的变量是不是数字,如果不是,通过continue进入下一次循环,finally是try成对出现的,无论如何都会执行的语句,所以i++放到这里

 

 3.通过arguments对象调取函数的参数

function f(x,y,z){
    if(arguments.length !=3){
        throw new Error("function f called with" + arguments.length + "arguments, but it expects 3 arguments.")
    }
    console.log(arguments[0],arguments[1],arguments[2])
}
//f(5,6,8)
try{
    f(5,6,9)
}
catch(e){
    alert(e);
}

throw neww error,通过try catch获取

4.通过arguments.callee 使匿名函数调用自身

(function(x){
    if(x<=1) return 1;
    return x*arguments.callee(x-1);
})(6)

posted on 2013-10-18 18:35  fishenal  阅读(192)  评论(0)    收藏  举报