search
HomeWeb Front-endJS TutorialAnalysis and explanation of recursive functions in JavaScript

Analysis and explanation of recursive functions in JavaScript

Nov 18, 2017 am 10:28 AM
javascriptjsillustrate

We have introduced to you the recursive function in php before. In fact, recursive functions are usually used more in the backend. For back-end developers, recursion should be a piece of cake, a very simple thing, but many front-end developers do not know much about this. In fact, recursion is often used in the front-end. Today we will analyze the recursive function in JavaScript!

js recursive call

// 一个简单的阶乘函数  var f = function (x) {  
    if (x === 1) {  
        return 1;  
    } else {  
        return x * f(x - 1);  
    }  };

The huge flexibility of functions in Javascript leads to difficulties in using function names during recursion. For the above variable declaration, f is A variable, so its value can be easily replaced:

var fn = f;  f = function () {};

The function is a value, which is assigned to fn. We expect to use fn(5) to calculate a value, but because the function still refers to variable f, so it doesn't work properly.

So, once we define a recursive function, we must be careful not to change the name of the variable easily.

What we discussed above are all functional calls. There are other ways to call functions, such as calling them as object methods.

We often declare objects like this:

var obj1 = {  
    num : 5,  
    fac : function (x) {  
        // function body  
    }  };

Declare an anonymous function and assign it to the object's attribute (fac).

If we want to write a recursion here, we have to reference the property itself:

var obj1 = {  
    num : 5,  
    fac : function (x) {  
        if (x === 1) {  
            return 1;  
        } else {  
            return x * obj1.fac(x - 1);  
        }  
    }  };

Of course, it will also suffer from the same problem as the function call:

var obj2 = {fac: obj1.fac};  
obj1 = {};  
obj2.fac(5); // Sadness

After the method is assigned to the fac attribute of obj2, obj1.fac still needs to be referenced internally, so... it fails.

Another way will be improved:

var obj1 = {  
     num : 5,  
     fac : function (x) {  
        if (x === 1) {  
            return 1;  
        } else {  
            return x * this.fac(x - 1);  
        }  
    }  };  var obj2 = {fac: obj1.fac};  obj1 = {};  obj2.fac(5); // ok

Use the this keyword to obtain the attributes in the context when the function is executed, so that when obj2.fac is executed, obj2 will be referenced inside the function fac attribute.

But the function can also be called by modifying the context arbitrarily, that is, the universal call and apply:

obj3 = {};  obj1.fac.call(obj3, 5); // dead again

So the recursive function cannot work properly.

We should try to solve this problem. Do you remember the function declaration method mentioned earlier?

var a = function b(){};

This method of declaration is called an inline function. Although the variable b is not declared outside the function, you can use b() to call yourself inside the function, so

var fn = function f(x) {  
    // try if you write "var f = 0;" here  
    if (x === 1) {  
        return 1;  
    } else {  
        return x * f(x - 1);  
    }  };  
    var fn2 = fn;  fn = null;  fn2(5); // OK  // here show the difference between "var f = function f() {}" and "function f() {}"  var f = function f(x) {  
    if (x === 1) {  
        return 1;  
    } else {  
        return x * f(x - 1);  
    }  };  var fn2 = f;  f = null;  fn2(5); // OK  var obj1 = {  
    num : 5,  
    fac : function f(x) {  
        if (x === 1) {  
            return 1;  
        } else {  
            return x * f(x - 1);  
        }  
    }  };  var obj2 = {fac: obj1.fac};  obj1 = {};  obj2.fac(5); // ok  var obj3 = {};  obj1.fac.call(obj3, 5); // ok

That's it, we have a name that we can use internally without worrying about who the recursive function is assigned to and how it is called.

The arguments object inside the Javascript function has a callee attribute, which points to the function itself. Therefore, you can also use arguments.callee to call functions internally:

function f(x) {  
    if (x === 1) {  
        return 1;  
    } else {  
        return x * arguments.callee(x - 1);  
    }  }

But arguments.callee is an attribute that is ready to be deprecated and is likely to disappear in future ECMAscript versions. In ECMAscript 5, "use strict", arguments.callee cannot be used.

The last suggestion is: if you want to declare a recursive function, please use new Function with caution. FunctionConstructorThe function created will be recompiled every time it is called. A function that is called recursively will cause performance problems - you will find that your memory is quickly exhausted.

js recursive function application

When I was working on a project recently, I used a recursive function to call the child nodes of json and put all the child nodes in json into objects containing a certain number. , are pushed into an array, and then bound to it.

I made the following recursive call

var new_array=[];
     function _getChilds(data){
         if(data.ObjType=="某个数"){
            new_array.push(cs_data);
        }
        if(data.Childs){
          if(data.Childs.length>0){
              getChilds(data.Childs)
          }
       }
     }
    function getChilds(data){
        for(var i=0;i<data.length;i++){
            _getChilds(data[i]);
        }
    }使用方法:getChilds("json数据")

to push all the data containing a certain number in json to the new_array array.

Summary:

I believe that through the above explanation, everyone will have a more advanced understanding of recursive functions. Recursive functions can not only Used in php, it can also be used in front-end JavaScript. I hope it will be helpful to you!

Related recommendations:

Refined understanding of recursive functions in JavaScript and sample code sharing

Recursive functions in JS

Introduction to the use of recursive functions in JS

The above is the detailed content of Analysis and explanation of recursive functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.