|
Introduction to XML in Flash
by senocular
Recursive Functions
Ok, so looping my not always be the
best idea. And yeah, sometimes you're going
to have complicated XML that will go levels
and levels deep. Sometimes you can't help this
- but also you don't want to have to make for
loops to handle all that. Have no fear; there
are other solutions. One is using recursive
function calls to handle like data no matter
how nested it is within your XML structure.
A recursive function is a function that calls
itself. This is, itself, a form of looping.
If you call a function that calls itself, then,
as it runs, it will call itself - a function
which, since its the same function, also calling
itself... which calls itself and so on and so
forth until something prevents the function
from calling itself again and all the previous
function calls resolve. Its just one big function
loop. For example, Math.pow, the function that
raises a number to a specific power can be written
as a recursive function:
- Math.pow
= function(num,
power){
- return (power
> 0)
? num*Math.pow(num,
power-1)
: 1;
- }
Math.pow, in this execution, checks to see
if pow is greater than 0. If so, it returns
the passed number times itself to the power
of the power passed minus 1 (by calling itself).
Effectively, what this does is counts power
down until its 0 returning that many multiplications
of the num argument times itself - one for each
call of Math.pow. In the end you have num to
the power-th power.
Recursive functions help you deal with problems
that are compounding or require like actions
to be performed repeatedly during a single operation
- much like looping. However, unlike looping,
the nesting of recursive functions is automatic
since each function call already contains another
call to itself. This provides for a theoretically
infinite number of nested calls, though, in
Flash, you're limited to using only 256. Loops
only become as nested when you write them out
to be. That flexibility and scalability is what
make recursive functions useful.
When dealing with XML recursion can be helpful
if you are unsure how deep your XML may go -
how many levels of children does each element
have? Though often you will (should) know exactly
how your XML is structured, sometimes you won't.
An example would be a dump of all the files
and folders (and the files and folders within
each folders) that are within a certain directory
of choice. This directory could be completely
empty or it could have folders upon folders
of files and other folders. You really don't
know. Using a recursive function to list out
each folder's contents would work really well
since once you've reached another folder, you
just call the function again to list out it's
contents, repeating the process until all subdirectories
have been listed.
|
|