您的位置:首页 > 移动开发 > Objective-C

Loop Through Object in Actionscript3.0

2011-11-01 14:52 405 查看
In Actionscript3.0, there is a method to iterate through an object:

var $obj:Object = {};

$obj.prop1 = "value-1";
$obj.prop2 = "value-2";
$obj.prop3 = "value-3";
$obj.prop4 = "value-4";

$obj["prop5"] = "value-5";

var $propname:String = "prop6";
$obj[$propname] = "value-6";

for (var $prop:String in $obj)
{
trace($prop + ": " + $obj[$prop]);
}

for (var $item in $obj)
{
trace($item);
}

for each (var $itemm in $obj)
{
trace($itemm);
}

will output:

prop3: value-3
prop6: value-6
prop1: value-1
prop4: value-4
prop5: value-5
prop2: value-2
prop3
prop6
prop1
prop4
prop5
prop2
value-3
value-6
value-1
value-4
value-5
value-2


Have no idea about why the order is 3-1-4-2!?, whatever, please note
the differences between 'for..in' and 'for each..in'.

This works because the variable '$obj' is weak-typed, and 'Object' should be dynamic class. It will not work on strong
typed object
. Let's try that. Create a class file: StrongObject.as

package  {

public class StrongObject {

public var prop1:String;
public var prop2:int;
public var prop3:Boolean;
public var prop4:Number;

public function StrongObject(
$val1:String,
$val2:int,
$val3:Boolean,
$val4:Number
)
{
this.prop1 = $val1;
this.prop2 = $val2;
this.prop3 = $val3;
this.prop4 = $val4;
}

}

}


And add the lines to .fla:

var $sobj:StrongObject = new StrongObject("test", 33, false, 45.6);

for(var $sprop:String in $sobj)
{
trace($sprop + ": " + $sobj[$sprop]);
}

That will output nothing!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: