1 2 3 4 5 6 7 8 9 10 | var sum = function(a, b){ return a+b; } var f = function fact(x){ if(x<= 1){ return 1; }else{ return x * fact(x-1); } } |
1 2 3 4 5 6 | var desc = function(a, b){ return a<b; } var a = [2,1,4,3,6,7]; a.sort(desc);// 把desc函数当作参数传给数组的sort方法 alert(a.join(','))// 输出7,6,4,3,2,1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var y = 'global'; function a(){ var y = 'local a'; return y; } alert(a());//显示'local a' var b = function(){ var y = 'local b'; return y; } alert(b()) //显示'local b' function c(){ var y = 'local c'; return new Function('return y'); } alert(c()());//显示'global',因为Function()返回的是全局变量y,而不是函数体内的局部变量。 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var start = new Date().getTime(); for(var i=0; i<10000000; i++){ var f = new Function(‘a’, ‘b’, ‘return a+b’); f(i, i+1); } var end = new Date().getTime(); alert(end-start);//结果显示~11s start = new Date().getTime(); var f = function(a, b){ return a+b; } for(var i=0; i<10000000; i++){ f(i, i+1); } end = new Date().getTime(); alert(end-start);//结果显示~7s |
1 2 3 4 5 6 7 8 9 10 11 12 | <code>alert (typeof f)//显示 function alert (typeof c)//显示 undefined,因为 c 还没有定义 alert (typeof d)//显示 undefined,因为 d 还没有定义 function f(){ return true } var c = function(){ return true; } alert(typeof c);//显示 function,上面已经定义,所以不是 undefined var d = new Function(‘return true’) alert(typeof d);//显示 function,上面已经定义,所以不是 undefined</code> |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |