Learning notes for JavaScript recursive functions

Source: Internet
Author: User

Recursive functions are called by the function itself. recursive functions are often used in non-hierarchical data applications, such as the unlimited classification of navigation menus. Next I will introduce the use of js recursive functions.

JavaScript supports recursive function calls.

The so-called recursive function is to call the function itself in the function body.

A common example of using recursive functions is factorial.

Use recursive functions to calculate 6! .

The Code is as follows: Copy code

<Script type = "text/javascript">
Function fact (num ){
If (num <= 1 ){
Return 1;
} Else {
Return num * fact (num-1 );
}
}
Document. write (fact (6 ));
</Script>

However, this may cause errors in js:

The Code is as follows: Copy code

Var anotherFactorial = factorial;
Factorial = null;
Alert (anoterFactorial (4 ));

Because the internal factorial does not exist when anoterFactorial is called.

The solution is solved through arguments. callee.

As follows:

The Code is as follows: Copy code

Function factorial (num)
{
If (num <= 1)
{
Return 1;
}
Else
{
Return num * arguments. callee (num-1 );
}
Var anotherFactorial = factorial;
Factorial = null;
Alert (anotherFactorial (4 ));
}

If we only need to call this function once in a very complex program, we certainly need to work hard to reduce the definition of function names for function streamlining, it is natural to think of using anonymous functions for direct execution. But how does an anonymous function implement recursion? Arguments. callee comes in handy. It refers to the reference of the currently executed function.

Arguments. callee
In javascript Functions, the identifier arguments has a special meaning. It is a special attribute of the called object and is used to reference the Arguments object. The Arugments object is like an array. Note that it is just like it is not. In a javascript function, arguments is like an array (not a real array, but an Arguments object, stressed again). It has the length attribute and can represent the number of parameters that can be passed to the function on behalf of the table.

You can use the parameter name or the arguments [] array to reference a formal parameter. arguments [0] indicates the first parameter. Therefore, the Arguments object in javascript is the actual parameter of the function. Next, let's take a look at this magical country.

Arguments. length attribute: js will not take the initiative to determine the number of parameters you have passed to the function. If you pass more parameters, the excess parameters will not be used. If you pass less parameters, the parameter value that is not passed is undefined.

So we can use the length attribute of arguments to check whether the actual parameters of the correct number are used when calling the function, because javascript will not do these tasks for you.

The Code is as follows: Copy code

Function f (x, y, z)
{
// First, check whether the number of passed parameters is correct.
If (arguments. length! = 3)
{
Throw new Error ("function f called with" + arguments. length + "arguments, but it not 3 arguments .");
}
// Run the real function below
}

Arguments also provides us with the possibility of passing any number of actual parameters for a function: for example, I want to determine the size of some numbers you pass to me, take out the largest one, right. That's right. You can upload any number of parameters, but only if you want to upload a number, because I am too lazy to judge it inside the function.

The Code is as follows: Copy code

Function max ()
{
Var m = Number. NEGATIVE_INFINITY; // Number. NEGATIVE_INFINITY: The smallest Number in JavaScript.
For (var I = 0; I <arguments. length; I ++)
{
// If any parameter is larger than m, m becomes the value of this parameter.
If (arguments [I]> m)
M = arguments [I];
}
Return m;
}

How is it? This method is very clever, right?

It indicates that arguments is consistent with the actually passed form parameter. For example, you pass a param parameter to the function, and only this parameter exists, in this case, both param and arguments [0] reference this parameter value and change one value, that is, all values of the two.

The Code is as follows: Copy code


Function change (param)
{
// For example, if my param is simaopig, alert is simaopig,
// If nothing is passed, alert undefined
Alert (param );
// Use arguments [0] to change the value of this parameter.
Arguments [0] = 'xiaoxiaozi ';
// Yes. The value is changed to xiaoxiaozi.
Alert (param );
}

The callee attribute of arguments: the callee attribute of arguments is used to reference the currently executed function, which is very good for untitled function calls.

Now we use the callee simple implementation of arguments.

The Code is as follows: Copy code

// Use the direct amount of functions and the arguments. callee attribute to implement recursive functions
Var result = function (x ){
If (x <= 1) return 1;
Return x * arguments. callee (x-1 );
};


The insurance method when js recursive functions call themselves.
Advanced JavaScript programming
A typical factorial recursive function:

The Code is as follows: Copy code
Function fact (num ){
If (num <= 1 ){
Return 1;
} Else {
Return num * fact (num-1 );
}
}

The following code can cause an error:

The Code is as follows: Copy code
Var anotherFact = fact;
Fact = null;
Alert (antherFact (4); // Error

Because fact is no longer a function, an error occurs.
Use arguments. callee to solve the problem. This is a pointer to the function being executed.
The new function is:

The Code is as follows: Copy code

Function fact (num ){
If (num <= 1 ){
Return 1;
} Else {
Return num * arguments. callee (num-1); // changed here.
}
}
Var anotherFact = fact;
Fact = null;
Alert (antherFact (4); // The result is 24.


Improvement of JS normal Recursion

A recursive function is formed when a function calls itself by name, as shown below:

The Code is as follows: Copy code
Function factorial (num)
{
If (num <= 1)
{
Return 1;
}
Else
{
Return num * factorial (num-1 );
}
}

This is a classic factorial function. On the surface, there seems to be no problem, but the following code may cause it to go wrong.

The Code is as follows: Copy code

Var anotherFactorial = factorial;

AnotherFactorial (4); // output 24
Factorial = null;
AnotherFactorial (4); // TypeError: Property 'factorial 'of object [object Window] is not a function chrome

Test
The reason is that the function name we define is actually a pointer to the function. At this time, we define anotherFactorial to point to that function, so calling anotherFactorial (4) can successfully output 24
In this case, factorial = null; anotherFactorial is left for the reference of the execution definition function, and the above error information is displayed when anotherFactorial (4) is called.
In this case, you can use arguments. callee to replace factorial in function definition,
The function is defined as follows:

The Code is as follows: Copy code
Function factorial (num)
{
If (num <= 1)
{
Return 1;
}
Else
{
Return num * arguments. callee (num-1 );
}
}

Then, when using the above four lines of test code, the last line of test code can also be successfully output 24.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.