zoukankan      html  css  js  c++  java
  • 函数二---递归

    // 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
  • 相关阅读:
    STL中的map
    HDU 4027 Can you answer these queries?
    HDU 2199 Can you solve this equation?
    USACO section1.2 Name That Number 命名那个数字
    HDU 3790 最短路径问题 (双重权值)
    [笔记]CiscoPT配置RIP
    [笔记]Cisco PT VLANTrunk配置
    iptables感悟Ubuntu
    CentOS网络配置
    Discuz X2 数据库备份功能分析
  • 原文地址:https://www.cnblogs.com/liululu/p/5939295.html
Copyright © 2011-2022 走看看