Recursive algorithm uses tips used in JavaScript (introduced by Object Packaging Method of JavaScript)

xiaoxiao2021-03-06  65

By Ben

For example, find 10!

There are two solutions:

French one:

General approach:

/ / ==================================== Document.writeln ("Recursive algorithm 1:"); / / ===================================== - 1); Document.writeln ("10! =" Factorial (10));

Method 2:

You can also perform recursive in the class method, but this is a bit risky. The method name of the Call class in JavaScript will be recursively caused "Object Expected" error. To avoid this error, you must use the basic function name or Callee parameter of the method to perform recursive. Based on the list D, I added a step-by-step method in mymath class, as shown below.

Document.writeln ("Recursive Algorithm 2:");

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));

转载请注明原文地址:https://www.9cbs.com/read-88453.html

New Post(0)