打印本文 打印本文 关闭窗口 关闭窗口
递归算法在javascript中使用的小技巧
作者:武汉SEO闵涛  文章来源:敏韬网  点击数652  更新时间:2009/4/23 11:29:42  文章录入:mintao  责任编辑:mintao

问题说明:比如求 10! 的结果
 
解决方法:有两种解法
法一
一般的做法
===========================
 document.writeln(br递归算法一br);
 ===========================
 function factorial(x) {
       if(x  2)
              return 1;
       else
              return x  factorial(x - 1);
 }
 
 document.writeln(10!= + factorial(10));
 
法二
还可在类的方法中执行递归,但这有点儿冒险。
在JavaScript中调用类的方法名来进行递归,会造成“Object Expected”错误。为避免这个错误,必须用方法的基本函数名或callee参数来执行递归。以清单D为基础,我在myMath类中添加了阶乘方法,如下所示。
 
document.writeln(br递归算法二br);

 function myMath() {
=======================================
  this.result;               Result of method
 
  this.factorial = myFactorial;     Factorial method
  function myFactorial(x) {
    if(x  2)
      return 1;
    else {
      this.result = x  arguments.callee(x - 1);
      return this.result;
    }
  }
=======================================
 }
 var math = new myMath();           Create an instance
 document.writeln(10! = + math.factorial(10));
 
 
详细解释 提高javascript代码的重用性,  推荐使用对象封装的方法来实现.
 
涉及技术:Web技术   作者:谭小鹏

 

打印本文 打印本文 关闭窗口 关闭窗口