• 函数二---递归


    // 7.1递归

    // 递归函数是在一个函数通过名字调用自身的情况下构成的,如下所示。

    function factorial(num){
    if(num<=1){
    return 1;
    }
    else{
    return num*factorial(num-1);
    }
    }
    var num1=factorial(4);
    console.log(num1);

    // 这是一个经典的递归阶乘函数,这个函数表面没有错误,但以下代码会使它报错。

    /* var anotherFactorial=factorial;
    factorial=null;
    console.log(anotherFactorial(4)); // 报错 factorial is not a function */

    // 以上代码会把factorial()函数保存在anotherFactorial变量中,然后将factorial变量置为null,结果指向
    // 原始函数的引用只剩下一个,但在接下来调用anotherFactorial()时,由于必须执行factorial(),而factorial
    // 已经不再是函数,所以就会导致错误,在这种情况下,可以使用arguments.callee解决

    function factorial2(num2){
    if(num2<=1){
    return num2;
    }
    else{
    return num2*arguments.callee(num2-1);
    }
    }
    factorial2(4);
    var anotherFactorial2=factorial2;
    factorial2=null;
    console.log(anotherFactorial2(4)); // 24

    // 通过使用arguments.callee代替函数名,可以确保无论怎样调用函数都不会出错。
    // 但是在严格模式下,不能通过脚本访问arguments.callee,可以使用函数表达式来达到一样的效果

    var factorial3=(function f(num){
    if(num<=1){
    return num;
    }
    else{
    return num*f(num-1);
    }
    });

    var anotherFactorial3=factorial3;
    factorial3=null;
    console.log(anotherFactorial3(4)); // 24
  • 相关阅读:
    模块(module)
    编译和解释性语言和python运行方式
    管道通信初级
    Page.TryUpdateModel 方法
    运用模型绑定和web窗体显示和检索数据(Retrieving and displaying data with model binding and web forms)
    HttpResponse 类
    ASP.NET中IsPostBack详解
    3.4.1 使用过滤式扩展方法(P43-44)
    使用扩展方法(Chapter3 P39-41)
    C#对象初始或器-Chapter3 P38
  • 原文地址:https://www.cnblogs.com/liululu/p/5939295.html
Copyright © 2020-2023  润新知