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

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

    function factorial (num){
      if (num <= 1){
        return 1;
      } else {
        return num* factorial(num-1)
      }
    }
    var anotherFactorical = factorial;
    console.log(anotherFactorical)
    factorial = null
    console.log(anotherFactorical(4))//出错

    函数的名字是一个指向函数对象的指针,如果把函数的名字与函数对象本身的指向关系断开,就会出错

    解决方法:

    arguments.callee(指向正在执行的函数的指针)

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

    严格模式下,不能通过脚本访问arguments.callee,访问这个属性会导致错误

    可以通过命名函数表达式来达成相同的结果

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

    console.log(f())
    f = null

    factorial = null
    console.log(f)
     console.log(anotherFactorical(4))//24

    即便把函数赋值给另一个变量,函数的名字f仍然有效,递归还能正常进行

    f()对外是不可见的

  • 相关阅读:
    「Codeforces 724F」Uniformly Branched Trees
    「笔记」组合入门题选做
    「算法笔记」组合入门与应用
    「算法笔记」可持久化线段树
    「算法笔记」期望 DP 入门
    「NOIP 2016」换教室
    「算法笔记」基础数论
    「笔记」关于乱搞
    python 的列表遍历删除
    Python基础第三篇:函数
  • 原文地址:https://www.cnblogs.com/psxiao/p/11372512.html
Copyright © 2011-2022 走看看