Home Web Front-end JS Tutorial Introduction to the use of recursive functions in js_javascript skills

Introduction to the use of recursive functions in js_javascript skills

May 16, 2016 pm 05:48 PM
recursive function

Let’s try a factorial within 10:


[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]



So much for calling recursive functions

The insurance method when js recursive functions call themselves.
From js advanced programming
A typical factorial recursive function: Copy code
The code is as follows:


function fact(num){
if (num<=1){
return 1;
}else{
return num*fact(num-1);
}
}


The following code can cause an error:
var anotherFact = fact;
fact = null;
alert(antherFact(4)); //Error

Because fact is no longer a function, an error occurred.
The problem can be solved with arguments.callee, which is a pointer to the function being executed.
The new function is: Copy the code
The code is as follows:


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.


Improvements of ordinary recursion in JS

Recursive functions are formed when a function calls itself by name, as follows: Copy code
The code is as follows:


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.
var anotherFactorial = factorial;

anotherFactorial(4); //Output 24
factorial = null;
anotherFactorial (4); //TypeError: Property 'factorial' of object [object Window] is not a function. Test under chrome
The reason is that the function name we defined is actually a pointer to the function. At this time, anotherFactorial is defined and also points to that function, so calling anotherFactorial (4) can successfully output 24
At this time, factorial = null; then the reference of the execution definition function is anotherFactorial. Then the above error message will be displayed when calling anotherFactorial(4).
At this time, you can use arguments.callee to replace factorial in the function definition.
The definition of the function becomes: Copy code
The code is as follows:


function factorial(num)
{
if(num<=1)
{
return 1;
}
else
{
return num * arguments.callee(num-1);
}
}


Then use the above 4 lines of test code, The last line of test code can also be successfully output 24. ---------------------------------------- -- The above content is excerpted from section 7.1 on page 144 of the 2nd edition of <>
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1249
24
What are the optimization techniques for C++ recursive functions? What are the optimization techniques for C++ recursive functions? Apr 17, 2024 pm 12:24 PM

To optimize the performance of recursive functions, you can use the following techniques: Use tail recursion: Place recursive calls at the end of the function to avoid recursive overhead. Memoization: Store calculated results to avoid repeated calculations. Divide and conquer method: decompose the problem and solve the sub-problems recursively to improve efficiency.

How to solve the excessive function nesting error in Python code? How to solve the excessive function nesting error in Python code? Jun 25, 2023 pm 12:35 PM

Python is a very powerful programming language, and many programmers choose Python as their main programming language. However, too much function nesting in the code can make the program difficult to maintain and understand. This article will explore how to solve the excessive function nesting error in Python code. A brief introduction to function nesting Function nesting refers to the process of defining another function in the body of a function. Function nesting can make the structure of the program clearer and the code easier to read and maintain. However, too many nested functions can lead to an overly complex code structure.

What are the exit conditions for a recursive function in C++? What are the exit conditions for a recursive function in C++? Apr 17, 2024 am 11:33 AM

The exit conditions of C++ recursive functions include: Baseline conditions: Check whether the function reaches a state that can directly return results, usually judging whether a certain condition or parameter value meets the threshold. Recursion termination condition: Alternative to or in addition to the baseline condition, ensuring that the function stops after a certain number of recursive calls, by tracking the recursion depth or setting a maximum recursion depth limit.

Application of C++ recursive functions in search algorithms? Application of C++ recursive functions in search algorithms? Apr 17, 2024 pm 04:30 PM

Recursive functions are used in search algorithms to explore tree-like data structures. Depth-first search uses a stack to explore nodes, while breadth-first search uses a queue to traverse layer by layer. In practical applications, such as finding files, recursive functions can be used to search for a given file in a specified directory.

C program to list all files and subdirectories in a directory C program to list all files and subdirectories in a directory Aug 25, 2023 pm 10:09 PM

Here we have a directory. Our task is to create a C program to list all files and subdirectories in a directory. A directory is a place/area/location where a set of file(s) will be stored. A subdirectory is a directory within the root directory, which, in turn, can have another subdirectory. In C programming language you can easily list all files and subdirectories in a directory. The following program shows how to list all files and subdirectories in a directory. //C program example to list all files and subdirectories in the directory Live demonstration #include<stdio.h>#include<dirent.h>intmain(void){ &am

How to implement factorial using recursive functions in Go language? How to implement factorial using recursive functions in Go language? Jul 31, 2023 pm 08:31 PM

How to implement factorial using recursive functions in Go language? Factorial is a common calculation in mathematics that multiplies a non-negative integer n by all positive integers smaller than it, up to 1. For example, the factorial of 5 can be expressed as 5!, calculated as 54321=120. In computer programming, we often use recursive functions to implement factorial calculations. First, we need to understand the concept of recursive functions. A recursive function refers to the process of calling the function itself within the definition of the function. When solving a problem, a recursive function will continually

Notes on details of recursive functions in Golang functions Notes on details of recursive functions in Golang functions May 16, 2023 am 08:09 AM

In Golang, recursion is a way for a function to call itself. Many problems can be solved using recursive functions, such as calculating factorials, Fibonacci sequences, etc. However, when writing recursive functions, you need to pay attention to some details, otherwise program errors may occur. This article will introduce the details of recursive functions in Golang to help developers write more stable and reliable recursive functions. Handling of basic situations When writing a recursive function, you first need to consider the basic situation, that is, the conditions for the exit of the recursive function. If there is no positive

How to implement the tail recursion optimization strategy of C++ recursive functions? How to implement the tail recursion optimization strategy of C++ recursive functions? Apr 17, 2024 pm 02:42 PM

The tail recursion optimization strategy effectively reduces the function call stack depth and prevents stack overflow by converting tail recursive calls into loops. Optimization strategies include: Detect tail recursion: Check whether there are tail recursive calls in the function. Convert functions into loops: Use loops instead of tail-recursive calls and maintain a stack to save intermediate state.

See all articles