Home > Web Front-end > JS Tutorial > A brief discussion on loop vs recursion_javascript skills

A brief discussion on loop vs recursion_javascript skills

WBOY
Release: 2016-05-16 17:41:14
Original
1111 people have browsed it

For example, traverse the following one-dimensional array:

Copy code The code is as follows:

[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:

Copy code The code is as follows:

[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:

Copy code The code is as follows:

[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.

Copy code The code is as follows:

[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:

Copy code The code is as follows:

[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

The code is as follows:[javascript] view plaincopyprint?var isArray = function(a) { return Object.prototype.toString.call(a) === '[object Array]'; };
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.
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