Home Web Front-end JS Tutorial Analysis and explanation of recursive functions in JavaScript

Analysis and explanation of recursive functions in JavaScript

Nov 18, 2017 am 10:28 AM
javascript js illustrate

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);  
    }  };
Copy after login

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 () {};
Copy after login

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  
    }  };
Copy after login

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);  
        }  
    }  };
Copy after login

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

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

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
Copy after login

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
Copy after login

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(){};
Copy after login

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
Copy after login

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);  
    }  }
Copy after login

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数据")
Copy after login

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 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 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
1655
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles