For...in Loops
by ilyas usal
for...in loops are tricky to use. What they
do is simple though: they reference everything they find in an object and put it
in an array. For instance, if we create two movie clips in the _root, and then
check what is in the _root, we will do it like that:
- _root.createEmptyMovieClip("firstClip",1);
- _root.createEmptyMovieClip("secondClip",2);
- var j;
- for (j
in _root)
- {
- trace (j+"
: "+this[j]);
- }
- /* returns
- j : j
- $version : WIN 6,0,21,0
- secondClip : _level0.secondClip
- firstClip : _level0.firstClip */
Not so hard, but you can see that it returns all sorts of things. Imagine
that we want to get the movie clips only.
- _root.createEmptyMovieClip("firstClip",1);
- firstClip.createEmptyMovieClip("secondClip",1);
- var j;
- for (j
in _root)
- {
- if (this[j]
instanceof MovieClip)
trace (j);
- }
- /* returns
- firstClip */
We only get the first clip because this time we created the second clip
INSIDE the first clip, so it is not in _root. To find all the clips on the
scene, we'd have to make a recursive function that checks inside all the clips
to find movie clip.
- _root.createEmptyMovieClip("firstClip",1);
- firstClip.createEmptyMovieClip("secondClip",1);
- MovieClip.prototype.searchClip
= function()
- {
- var j;
- for (j
in this)
- {
- if
(this[j]
instanceof
MovieClip)
- {
- trace
(j);
- this[j].searchClip();
- }
- }
- }
- _root.searchClip();
- /* returns
- firstClip
- secondClip */
In the first 2 lines of our script, we create a first clip, and inside it a
second clip. Then we define our function (in fact a prototype, look for a text
about them here). The prototype checks the object that called it first, checks
whether what it finds is a movie clip, and if so applies itself to that object.
That's called recursion.
It is also practical to browse through arrays:
- myArray =
new Array
("Kirupa","Supra","Upuaut","Ahmed","Eyez","Ahmed","Jubby");
- count=0;
- var j;
- for (j
in myArray)
- {
- count++;
- }
- trace ("There
are "+count+"
elements in myArray");
- /* returns There are 7 elements in myArray */
It works. But you have to be careful, because if you define an array
prototype, it will appear in the list.
- Array.prototype.myPrototype
= function
() {}
- myArray =
new Array
("Kirupa","Supra","Upuaut",Ahmed","Eyez","Ahmed","Jubby");
- count=0;
- var j;
- for (j in myArray)
- {
- count++;
- }
- trace ("There
are "+count+"
elements in
myArray");
- /* returns there are 8 elements in myArray
- This includes the prototype, even tough
- there is nothing in it */
Hope this tutorial helped. If you have any
questions, please post them on the forums at
//www.kirupa.com/forum/

|