search
HomeWeb Front-endJS TutorialIntroduction to recursion and loop examples of JavaScript recursion_javascript skills

Recursion and Loop

For different types of problems that require repeated calculations, loop and recursion methods have their own advantages and can provide more intuitive and simple solutions. On the other hand, loop and recursive methods can be converted into each other. Any loop of code can be rewritten using recursion to achieve the same function; and vice versa. Without losing their generality, loops and recursions can be summarized using the following pseudocode.

Pseudocode format description: The loop adopts the while form; variables are not defined; assignment uses:=; conditional expressions and executed statements are written in the form of functions, and relevant values ​​are written in parentheses. In terms of other syntax, try to be as close to Javascript specifications as possible.
Copy code The code is as follows:

//pseudo code of a loop
// while form
function loop(arguments){
//The initial value of the result
result:=initial_value;

while(condition(variable, arguments)){//Loop condition, possible Only arguments are required, and loop variables may also be introduced for convenience
//Calculation results. Parameters include previous results, current loop variables and external variables
result:=calculate(result, variable, extern_variables);
//Affect the external environment of the function, that is, modify external variables
changeStatus(result, variable , extern_variables);
//After executing the statements in the loop body, modify the parameters or loop variables.
modify_arguments_variable(arguments, variable);
}
//Return result
return result;
}

Similarly we give the pseudo code of the recursive function.
Copy code The code is as follows:

//pseudo code of a recursion
function recursion (arguments){
//The following code is the structural part that controls the repeated calling of the function.
//Get new parameters for calling this function again, which may be multiple sets of argument values.
//Corresponds to condition(variable, arguments) and modify_arguments_variable(arguments, variable) in the loop.
new_arguments:=conditional_get_next(arguments);
//For each group of new parameters, call the function itself.
results:=recursion(new_arguments);

//The following code is the functional part that is run every time it is called.
//Calculate the results. Involves previous results, current loop variables and external variables.
//Corresponds to result:=calculate(result, variable, extern_variables) in the loop.
result:=calculate(arguments, extern_variables);
result:=combine(result, results);
//Affect the external environment of the function, that is, modify the external variables
changeStatus(result, arguments, extern_variables);
return result;
}

Comparing the two pieces of code, we can see that loops and recursions have similar compositions. By changing the order and appropriate transformations, any loop can Can be implemented recursively. This transformation is easy to see when the program is simple. For example, the following simple cumulative sum function:
Copy code The code is as follows:

// loop
function sum(num){
var result=1;
while (num>1){
result =num;
num--;
}
return result;
}

The corresponding recursive form:

Copy code Code As follows:

//recursion
function sum2(num){
if (num>1){
return num sum(num-1);
}else {
return 1;
}
}

Conversely, most recursive programs can also be implemented directly by loops. The following is a function in the form of a loop that finds the greatest common divisor.
Copy code The code is as follows:

function gcd2(a, b){
var temp;
if (atemp=a;
a=b;
b=temp;
}
var c=a%b;
while (c!==0){
a=b;
b=c;
c=a%b;
}
return b;
}

However, the transition from recursion to looping is not always easy. The part in the recursive pseudocode that generates new arguments for calling this function again

new_arguments:=conditional_get_next(arguments);

is more flexible than the corresponding part of the loop. Recursion can be divided into two categories according to the number of newly generated parameter groups (all parameters required by the function are one group). The first type is when the number of parameter groups is fixed, and the recursion can be converted into a loop, such as the Fibonacci sequence and the greatest common divisor example; the second type is when the number of parameter groups is uncertain - just like when traversing a graph or tree That way, each point has any number of adjacent points - this recursion cannot be directly converted into a loop.

Because loops can only do one-dimensional repetitions, while recursion can traverse two-dimensional structures. For example, in a tree, a node has both its child nodes and nodes at the same level. A simple one-dimensional loop cannot traverse in both directions.

But the second type of recursion can also be implemented with loops if we remember some information about the node position with the help of some data structure.

Let’s use another example to practice the conclusion drawn from the above observation. HTML5 defines a new method getElementsByClassName(names) for Document and Element, which returns all elements with a given class value. Some browsers, including Firefox 3, already support this method. Below we first use a recursive method to give a weaker version, and then rewrite it using a loop method.
Copy code The code is as follows:

var getElementsByClass={};

//elem is an HTMLElement
//name is a single class name
//returns an array containing elements with all class attributes under elem containing the given name
getElementsByClass.recursion1=function (elem, name){
var list=[];
function getElements(el){
if (el.className.split(' ').indexOf(name)>-1){
list.push( el);
}
for (var i=0, c=el.children; igetElements(c[i]);
}
}
getElements(elem);
return list;
}

As mentioned before, in order to remember the position information of the node in the loop, we need a function that can implement the following The data structure of the method.

push(object) //Write an object.

objectpop() //Read the most recently written object and delete it from the data structure.

objectget() //Read the most recently written object without changing the contents of the data structure.

The stack is exactly such a last-in-first-out data structure. The Array object in Javascript supports the first two methods, and we can add a third method to it.

The looped version:
Copy the code The code is as follows:

getElementsByClass .loop1 = function(elem, name){
//use a js array as the basis of a needed stack
var stack = [];
stack.get = function(){
return stack[stack.length - 1];
}

var list = [];
//the business logic part. put the eligible element to the list.
function testElem(el ){
if (el.className.split(' ').indexOf(name) > -1) {
list.push(el);
}
}
// check the root element
testElem(elem);
//initialize the stack
stack.push({
pointer: elem,
num: 0
});
var parent, num, el;
while (true) {
parent = stack.get();
el = parent.pointer.children[parent.num];
if (el) { //enter a deeper layer of the tree
testElem(el);
stack.push({
pointer: el,
num: 0
});
}
else {//return to the upper layer
if (stack.pop().pointer === elem) {
break;
}
else {
stack.get() .num = 1;
}
}
}

return list;
}

To sum it up. All loops can be implemented using recursion; all recursion can be implemented using loops. Which method is used depends on which idea is more convenient and intuitive for specific problems and the user's preferences.

Efficiency

In terms of performance, recursion has no advantage over loops. In addition to the overhead of multiple function calls, recursion can also lead to unnecessary repeated calculations in some cases. Take, for example, a recursive program that calculates the Fibonacci sequence. When finding the nth item A(n), starting from the n-2nd item, each item is calculated repeatedly. The smaller the number of items, the more times it is repeated. Let B(i) be the number of times the i-th item is calculated, then there is

B(i)=1; i=n, ​​n-1

B(i)=B(i 1) B(i 2); i
In this way, B(i) forms an interesting inverse Fibonacci sequence. When finding A(n):

B(i)=A(n 1-i)

Looking at it from another perspective, let C(i) be when finding A(i) The number of additions required is:

C(i)=0; i=0, 1

C(i)=1 C(i-1) C(i-1) ; i>1

Let D(i)=C(i) 1, there is

D(i)=1; i=0, 1

D(i )=D(i-1) D(i-1)

So D(i) forms another Fibonacci sequence. And it can be concluded:

C(n)=A(n 1)-1

And A(n) grows in a geometric series. This redundant repetition increases when n is smaller. It becomes quite astonishing when it gets bigger. The corresponding program using loops has

B(n)=1; n is any value

C(n)=0; n=0, 1

C(n)=n-1; n>1

Therefore, when n is large, the program using loops given above will be much faster than the program using recursion.

Like the loop in the previous section, this flaw in recursion can also be made up for. We only need to remember the terms that have been calculated, and when finding higher terms, we can directly read the previous terms. This technique is common in recursion and is called memorization.

The following is a recursive algorithm for finding the Fibonacci sequence using storage technology.
Copy code The code is as follows:

//recursion with memorization
function fibonacci4(n ){
var memory = []; //used to store each calculated item
function calc(n){
var result, p, q;
if (n memory[n] = n;
return n;
}
else {
p = memory[n - 1] ? memory[n - 1] : calc(n - 1);
q = memory[n - 2] ? memory[n - 2] : calc(n - 2);
result = p q;
memory[n] = result;
return result;
}
}
return calc(n);
}
Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.