JS function-I call myself try

Source: Internet
Author: User

Objective

Recently read the "JavaScript language essence", the recursive function has a further understanding, hoping to summarize:

Recursion is a powerful programming technique that decomposes a problem into a set of similar sub-problems, each of which is solved with an ordinary solution. A recursive function is a function that calls itself directly or indirectly, in general, a recursive function calls itself to solve its sub-problems.

The classic recursive problem of "Hanoi"

"Hanoi" is an ancient Indian legend, but also the classic recursion problem in program design, is a famous puzzle game:

The topics are as follows:

There are three pillars on the tower and a set of hollow discs of different diameters, and all the discs on the source pillars are arranged in order from large to small in the beginning. The goal is to move a disk to another pillar each time, eventually moving a pile of discs to the target column, the process is not allowed to place the larger disk on the smaller disk;

    

Find the pattern (move all the discs to C):

1) n (number of discs) = = 1

First time: Number 1th, A-C sum (number of moves) = 1

2) n = = 2

First: Plate 1th, A-B

Second time: Plate 2nd, A-C

Third: Number 1th, B-C sum = 3

3) n = = 3

First: Plate 1th, A-C

Second time: Plate 2nd, A-B

Third: Plate 1th, C-B

Fourth time: Plate 3rd, C

Fifth time: Plate 1th, B, A

Sixth time: Plate 2nd, B, C

Seventh time: Number 1th, A-C sum = 7

etc...

So it is not difficult to find the law, the number of moves: sum = 2^n-1

Algorithm Analysis (Recursive):

Move a pile of discs from one pillar to another, using auxiliary pillars if necessary. You can divide it into three sub-problems:

First, move the smaller discs in a pair of discs to the auxiliary pillars, exposing the larger discs below,

Next, move the disc below to the target column.

Finally, move the smaller disc from the auxiliary pillar to the target post.

Turn three steps into a simple math problem:

(1) Move the n-1 plate from a to B;

(2) Move the nth plate from a to C;

(3) Move the n-1 plate from B to C;

We create a JS function that, when it calls itself, handles the disk that is currently working on the disk. Finally it goes back to a non-existent disk to call, in which case it is not performing any operations.

JavaScript Source code implementation
var function (DISC,SRC,AUX,DST) {     if(disc>0) {        Hanoi (disc-1, src,dst,aux);        Console.log (' mobile ' + disc +  ' disk ' + ' move from ' + src +  ' to ' +  DST ');        Hanoi (Disc-1, AUX,SRC,DST)    }}hanoi (3, ' A ', ' B ', ' C ')

The whole idea of the algorithm is:

    1. Temporarily move the n-1 plate on the A pillar to the B pillar.
    2. A pillar has only the largest plate left, move it to the target column C.
    3. Finally, move the n-1 plate on the B pillar to the target column C.

JS recursive function Traversal DOM

Recursive functions can operate the tree structure very efficiently, and in JavaScript there is a "natural tree structure" of the Document Object Model (DOM) on the browser side. Handles a small segment of the specified tree each time a recursive call is invoked.

/*we define a walk_the_dom function, 1) It starts from a specified node, accesses each node of the tree in the order of the specified HTML source code 2) It invokes a function, passes each node in turn, and Walk_the_dom calls itself to process each node */varWalk_the_dom =functionWalk (node, func) {func (node); Node=Node.firstchild;  while(node) {Walk (node, func); Node=node.nextsibling; }    }/*in the definition of a Getelementbyattribute function 1) It takes a property name string and an optional matching value as parameter 2) it calls Walk_the_dom and passes a function to find the name of the node property as a parameter. The matching nodes will be added to an array.*/       varGetelementsbyattribute=function(att,value) {varresults=[]; Walk_the_dom (Document.body,function(node) {varactual=node.nodetype===1&&Node.getattribute (ATT); if(typeofactual=== ' String ' && (actual===value| |typeofvalue!== ' String ') {Results.push (node);      }         }); returnresults; }

Named function expressions and recursive recursion problems

function to find factorial:

function factorial (num) {    if(num<=1) {        return 1;    } Else {        return num*factorial (num-1);    }}

By setting the function factorial to null so that the reference to the original function is only one, the factorial is no longer a function

Arguments.callee Implementing recursion

Arguments.callee is a pointer to a function that is executing, so it can be used to implement recursive calls to functions

function factorial (num) {    if(num<=1) {        return 1;    } Else {        return Num*arguments.callee (num-1);    }} var anotherfactorial=factorial;factorial=null; anotherfactorial ( // 6

Using Arguments.callee instead of a function name ensures that no matter how the function is called, there will be no problem. Therefore, when writing recursive functions, using Arguments.callee is always more insured than using the function name.

However, in strict mode, Arguments.callee cannot be accessed through a script, and accessing this property will cause an error

Named function expressions Implement recursion

Create a named function expression named F (), and then assign to factorial, even if the function is assigned to another variable, the function's name F is still valid, so the recursive call can be completed normally.

This approach is feasible in both strict and non-rigid modes.

var factorial =function  f (num) {    ' use strict '    if(num<=1) {         return 1;    } Else {        return num* F (num-1);    }} Factorial (3)    //6var anotherfactorial=factorial;factorial =null; anotherfactorial (3)      //6

Write it in the back.

Why not try to make yourself love while others are "holding on"? Because of love, so we pay, but it is because of the pay, so we can only love more.

College students a Caishuxueqian, if there is a mistake, but also look at the elder.

JS function-I call myself try

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.