The for-in Loop
A for-in
statement is a specialized loop used to
list the properties of an object. New programmers
may want to skip this section for now and return to it after reading
Chapter 12.
Rather than repeating a series of statements until a given test
expression yields the value false
, a
for-in
loop iterates once for each property in
the specified object. Therefore, for-in
statements do not need an explicit update statement because the
number of loop iterations is determined by the number of properties
in the object being inspected. The syntax of a
for-in
loop looks like this:
for (varthisProp
inobject
) {substatements
; // Statements typically use thisProp in some way }
The
substatements
are executed once for each property of
object
; object
is the name of any valid object; thisProp
is any variable name or identifier name. During each loop iteration,
the thisProp
variable temporarily holds a
string that is the name of the object property currently being
enumerated. That string value can be used during each iteration to
access and manipulate the current property. The simplest example of a
for-in
loop is a script that lists the
properties of an object. Here we create an object and then itemize
its properties with a for-in
loop:
var ball = new Object( ); ball.radius = 12; ball.color = "red"; ball.style = "beach"; for (var prop in ball) { trace("ball has the property " + prop); }
Because prop
stores the names of the properties of
ball
as strings, we can use
prop
with the []
operator ...
Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.