recursive function: refers to the function directly or indirectly called the function itself, it is said that the function is a recursive function.
This sentence is not difficult to understand, from a conceptual point of view, give the following examples:
function foo () { console.log ("function foo is a recursive function.) "); Foo ();}
The Foo function of this example is a recursive function.
When you take this function to the browser to run, you will find that the memory overflow, why? Because this recursive function does not stop processing or operation of the exit, so
This recursive function evolves into a dead loop.
So how do you use recursion?
There are two conditions that must be met to use a recursive function:
1, in each call to themselves, must be (in a sense) closer to the solution;
How do you understand this sentence?
Do you have stairs at home? For example, from the first floor to the second floor, then our starting point is the first floor, the destination is the second floor, when you go up each step is not the closer to the second floor, that is, the closer to the destination.
So this sentence can be understood as follows: Each time the function calls itself, the closer it is to the end of the task we expect it to accomplish.
2, must have a termination processing or calculation of the export.
This means that there must be a standard flag that allows the function to end the invocation of the function itself.
For example, how do you know you've reached the second floor? When you see a door that says 2F on the house, and pushes it across, you're on the second floor.
Recursively outputs all the property values contained in the object (including descendants of objects in the object):
varobj ={a:{Name:"John", Age:26, Sex:"Male", child:{firstchild:"Mak", Lasechild:"Loy"}}, b:{name:"Joe", Age:28, Sex:"Female", child:{firstchild:"Bill.", Secondchild:"Ruth", Lasechild:"Yoki" } }};functionGetobjvalue (obj) { for(varKinchobj) {if(typeofObj[k]!== "Object") {Console.log (obj[k]);//Recursive exit}Else{getobjvalue (obj[k]);//function Call function itself}}};getobjvalue (obj);//Output Result://Name=john//age=26//Sex=male//Firstchild=mak//Lasechild=loy//Name=joe//age=28//Sex=female//Firstchild=bill//Secondchild=ruth//Lasechild=yoki
Usage advice: When using recursion, pay attention to checking the parameter types of the recursive function, and ensure that there is an exit to terminate processing or calculation. Otherwise it is easy to evolve into a dead loop, which can cause memory overflow.
JavaScript recursive functions