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

Analysis and explanation of recursive functions in JavaScript

黄舟
Release: 2017-11-18 10:28:58
Original
2210 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template