


Introduction to recursion and loop examples of JavaScript recursion_javascript skills
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.
//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.
//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:
// loop
function sum(num){
var result=1;
while (num>1){
result =num;
num--;
}
return result;
}
The corresponding recursive form:
//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.
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.
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; 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:
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.
//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);
}

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.

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 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 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 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.

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.

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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.