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()对外是不可见的

  • 相关阅读:
    图像梯度计算
    图像轮廓检测
    元组()
    SwiftUI 概览
    TCL 语言概览
    列表 []
    Numpy 矩阵计算
    图像平滑(滤波)
    language="JavaScript"与type="text/javascript"
    调用接口, Test.java(不用任何包, MD5大写32位加密,HttpURLConnection)
  • 原文地址:https://www.cnblogs.com/psxiao/p/11372512.html
Copyright © 2011-2022 走看看