The code in this article uses JavaScript. Some people's understanding of recursion is still stuck in "It is an inefficient method to calculate factorial than loop ". Actually, recursion and loop processing are different. Taking the "traversal array" issue for example: loops are suitable for traversing on the same dimension (with unlimited single-layer length), while recursion is suitable for Traversing across dimensions (with unlimited layers. For example, traverse the following one-dimensional array:
The Code is as follows:
[Javascript] view plaincopyprint?
Var a1 = [1];
Var a2 = [1, 2];
Var a3 = [1, 2, 3];
Although they have different lengths, it is very easy and elegant to deal with them cyclically:
The Code is as follows:
[Javascript] view plaincopyprint?
Var dumpArrayByLoop = function (){
For (var I = 0; I <a. length; I ++ ){
Println (a [I]);
}
};
If recursion is used, it looks awkward:
The Code is as follows:
[Javascript] view plaincopyprint?
Var dumpArrayByRecur = function (I, ){
If (I <a. length ){
Println (a [I]);
DumpArrayByRecur (I + 1, );
}
};
They can output the same results, but the recursive version looks clumsy.
Now, if the metadata changes, the dimension is extended to two-dimensional.
The Code is as follows:
[Javascript] view plaincopyprint?
Var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9];
At this point, you need to set another loop to a dual loop:
The Code is as follows:
[Javascript] view plaincopyprint?
Var dumpArrayByLoop = function (){
For (var I = 0; I <a. length; I ++ ){
For (var j = 0; j <a [I]. length; j ++ ){
Println (a [I] [j]);
}
}
};
If the data dimension continues to expand, it will become three-dimensional and four-dimensional ...... Even a dynamic n-dimensional array. What should I do if I use a loop?
In such a situation that the number of layers is very deep or even uncertain, we need to use recursion to solve the problem of cross-layer.
The Code is as follows:
[Javascript] view plaincopyprint?
Var isArray = function (){
Return Object. prototype. toString. call (a) = '[object Array]';
};
Var dumpArrayByRecur = function (){
If (isArray ()){
For (var I = 0; I <a. length; I ++ ){
DumpArray (a [I]);
}
} Else {
Println ();
}
};
In the code above, if a subnode is found to be an array, It is recursively entered into the next layer, and traversal on the same layer is completed through loops.