2007年5月30日星期三

for..in and for each..in

ActionScript 3 has a new iteration statement: for each..in (for each..in). for each..in works much like for..in (for..in) execpt it loops through the values of an object rather than its keys. Example:

ActionScript Code:

var object:Object = new Object();
object.name = "senocular";
object.id = 2867;
object.isModerator = true;
for each (var value:* in object){
trace(value);
}
/* Output:
true
2867
senocular
*/


Respectively, a for..in would look like:

ActionScript Code:

var object:Object = new Object();
object.name = "senocular";
object.id = 2867;
object.isModerator = true;
for (var key:String in object){
trace(key + ": " + object[key]); // object[key] is value
}
/* Output:
isModerator: true
id: 2867
name: senocular
*/


Note that the key is not available in for each..in.

ActionScript 3 also maintains array element order (using numeric array indices) when using for..in and for each..in rather than basing order off of when the value was created as was the case in ActionScript 1 and 2. Example:

ActionScript Code:

var array:Array = new Array();
array[1] = 1;
array[0] = 2;
array[2] = 3;
for (var key:String in array){
trace("array[" + key + "] = "+ array[key]);
}


Output AS 1 & AS 2:

Code:

array[2] = 3

array[0] = 2

array[1] = 1

Output AS 3:

Code:

array[0] = 2

array[1] = 1

array[2] = 3

This provices a more intuitive order when iterating through arrays with for..in and for each..in.

Note: To use the for each..in statement with an instance of a user-defined class, you must declare the class with the dynamic attribute.

0 评论: