首页 > Web开发 > 详细

JS中的递归函数

时间:2020-04-04 23:31:28      阅读:68      评论:0      收藏:0      [点我收藏+]
// 经典的写法
    function test(n) {
        if (n <= 1) {
            return 1;
        } else {
            return  n * test(n-1);
        }
    }
    test(4) // 24

上面的写法是没有问题的 ,但是如果遇到函数表达式的写法,可能会报错,比如:

 function test(n) {
        if (n <= 1) {
            return 1;
        } else {
            return  n * test(n-1);
        }
    }
    var t = test;
    test = null;
    t(); // test is not a function

这就是函数调用函数的弊端,那怎么解决呢,用 arguments.callee 来解决,但是arguments.callee 这个方法被弃用了,所以我们用的时候,要注意使用场景和使用方法:

1.使用递归的时候,函数是声明式的写法(声明式函数和表达式函数自行百度,或者看我另外一篇博客),避免出现 test is not a function 这种错误

2.参考文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments/callee

 

JS中的递归函数

原文:https://www.cnblogs.com/0955xf/p/12634307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!