For example, traverse the following one-dimensional array:
[javascript] view plaincopyprint?
var a1 = [1];
var a2 = [1, 2];
var a3 = [1, 2, 3];
Although they vary in length, it is very easy and elegant to loop through them:
[javascript] view plaincopyprint?
var dumpArrayByLoop = function(a) {
for (var i = 0; i < a.length; i ) {
println(a[i]);
}
};
If you use recursion instead, it will look awkward:
[javascript] view plaincopyprint?
var dumpArrayByRecur = function(i, a) {
if (i < a.length) {
println(a[i]);
dumpArrayByRecur(i 1, a);
} }
} ;
They output the same result, but the recursive version looks clunky in comparison.
Now think about it, if the metadata changes: the dimension expands to two dimensions.
[javascript] view plaincopyprint?
var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
At this time, you need to add another layer of loop outside to form a double loop:
[javascript] view plaincopyprint?
var dumpArrayByLoop = function(a) {
for (var i = 0; i < a.length; i ) {
for (var j = 0; j < a[i].length; j ) {
println(a[i][j]); Dynamic N-dimensional array. How to deal with using loops?
In this situation where the number of "layers" is very deep or even uncertain, "recursion" needs to be used to solve cross-"layer" problems.
Copy code
var dumpArrayByRecur = function(a) {
if (isArray(a)) {
for (var i = 0; i < a.length; i ) {
dumpArray(a[i]);
} else {
println(a);
}
};
In the above code, if the child node is found to be an array, recursion is used to enter the next level; while traversal on the same level is completed using loops.