Loop Through Object in Actionscript3.0

本文探讨了ActionScript 3.0中通过多种方式遍历对象的方法,包括使用for...in、foreach...in循环,解释了不同遍历方法的输出顺序,并通过创建强类型对象类演示了强类型对象在遍历时的表现。
摘要由CSDN通过智能技术生成

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!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值