比如求 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类中添加了阶乘方法,如下所示。
this.result; //Result of method
this.factorial = myFactorial; //Factorial method
if(x < 2)
return 1;
else {
this.result = x * arguments.callee(x - 1);
}
}
}
document.writeln("10! =" + math.factorial(10));
223




被折叠的 条评论
为什么被折叠?



