1.递归
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS自定义函数</title> <script type="text/javascript"> var a=0,b=0; // 直接调用 function test1(){ console.debug(a); if(++a<5){ test1(); } } // 间接调用 function test2(){ console.debug("this is test2 b="+b); if(++b<5){ test3(); } } function test3(){ console.debug("this is test3"); test2(); } </script> </head> <body> <input type="button" value="test1" onclick="test1()"> <input type="button" value="test2" onclick="test2()"> </body> </html>
先后分别电机test1、test2按钮,后台运行结果:
经典案例:汉诺塔
// 汉诺塔 var n=3; function hanoi(n){ // 将n个盘子从A柱借助B柱移动到C柱 move(n,'A','B','C'); } function move(n,from,middle,to){ if(n==1){//如果只有一个盘子就直接移动到目标柱 console.debug(n+":"+from+"-->"+to); } else{ // 先将n-1个盘子从起始柱借助目标柱移动到中间柱 move(n-1,from,to,middle); // 再将最后一个盘子从起始柱移到目标柱 console.debug(n+":"+from+"-->"+to); // 最后将n-1个盘子从中间柱借助起始柱移到目标柱 move(n-1,middle,from,to); } }
演示结果:
- 补充:能够使用循环的尽量使用循环解决问题
2.回调
<script type="text/javascript"> function getMax(a,b){ return a>b?a:b; } function test1(){ doCompare(3,7,getMax); } function doCompare(a,b,compare){ var ret=compare(a,b); console.debug(a+"、"+b+"中最大值为:"+ret); } </script>后台运行结果:
3.匿名函数
- 没有函数名的函数;一般用于回调,也可能用于一次性执行的函数,执行完成后自动销毁,节省空间。