JavaScript 函数和递归
1 函数的两种使用方式:第一函数声明,第二函数表达式,写法如下:
- <script>
- function test1() { //函数的声明alert("test1");}test1();var test2=function(){//函数表达式alert("test2");};test2();
- </script>
区分函数声明和函数表达式:最重要的是理解函数声明的提升,即在执行代码前先会读取函数的声明,意外着可以把函数的声明放到函数的调用之后,并不会报错。然而对于函数表达式不行。
2 递归
三种递归的方式:
1 常见的写法:
- function test(num) {
- if (num <= 1) {
- return 1;
- } else {
- return num + test(num - 1);
- }
- }
- var anothertest = test; //test=null;//这两行代码会导致上诉的递归函数调用错误
2 arguments.callee() 是一个指向正在执行的函数的指针,可用它实现递归
- function test(num) {
- if (num <= 1) {
- return 1;
- } else {
- return num + arguments.callee(num - 1);
- }
- }
这种写法在非严格模式下没问题。
3 严格模式下的递归调用 (非严格也行)
- <script>
- var test1 = (function test(num) {
- if (num <= 1) {
- return 1;
- } else {
- return num + test(num - 1);
- }
- });
- alert(test1(4));
- </script>
通过创建一个 test() 命名函数表达式。
就爱阅读 www.92to.com 网友整理上传, 为您提供最全的知识大全, 期待您的分享,转载请注明出处。
来源: http://www.92to.com/bangong/2017/03-17/18939562.html