JavaScript 递归函数怎么调用自身? 下面本篇文章给大家介绍一下 JavaScript 递归函数中调用自身的写法. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
1一般的通过名字调用自身
- function sum(num){
- if(num<=1){
- return 1;
- }else{
- return num+sum(num-1);
- }
- }
- console.log(sum(5));//15
这种通过函数名字调用自身的方式存在一个问题: 函数的名字是一个指向函数对象的指针, 如果我们把函数的名字与函数对象本身的指向关系断开, 这种方式运行时将出现错误.
- function sum(num){
- if(num<=1){
- return 1;
- }else{
- return num+sum(num-1);
- }
- }
- console.log(sum(5));//15
- var sumAnother=sum;
- console.log(sumAnother(5));//15
- sum=null;
- console.log(sumAnother(5));//Uncaught TypeError: sum is not a function(...)
2通过 arguments.callee 调用函数自身
- function sum(num){
- if(num<=1){
- return 1;
- }else{
- return num+arguments.callee(num-1);
- }
- }
- console.log(sum(5));//15
- var sumAnother=sum;
- console.log(sumAnother(5));//15
- sum=null;
- console.log(sumAnother(5));//15
这种方式很好的解决了函数名指向变更时导致递归调用时找不到自身的问题. 但是这种方式也不是很完美, 因为在严格模式下是禁止使用 arguments.callee 的.
- function sum(num){
- 'use strict'
- if(num<=1){
- return 1;
- }else{
- return num+arguments.callee(num-1);
- }
- }
- console.log(sum(5));
- //Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not
- // be accessed on strict mode functions or the arguments objects for calls to them(...)
3通过函数命名表达式来实现 arguments.callee 的效果.
- var sum=(function f(num){
- 'use strict'
- if(num<=1){
- return 1;
- }else{
- return num+f(num-1);
- }
- });
- console.log(sum(5));//15
- var sumAnother=sum;
- console.log(sumAnother(5));//15
- sum=null;
- console.log(sumAnother(5));//15
这种方式在严格模式先和非严格模式下都可以正常运行.
更多 web 前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/javascript/17395.html