AS3 对复杂对象的排序规则[DEMO]

源代码:

package
{
	import flash.display.Sprite;
	
	/**
	 *  测试复杂对象的排序
	 * @author Jave.Lin(afeng)
	 **/
	public class TestComplexSort extends Sprite
	{
		public function TestComplexSort()
		{
			super();
			
			var lastNameArr:Vector.<String>=new Vector.<String>();
			lastNameArr.push("Lin","Smith","Steven","Abros","BB","CCC","D","EE","FF","GG","Gates","HH");
			
			var firstNameArr:Vector.<String>=new Vector.<String>();
			firstNameArr.push("Jave","John","Harry","Waston","Bill","Tom","Jerry");
			
			var ageMax:uint=150;
			
			var personArr:Vector.<Person>=new Vector.<Person>();
			
			for (var i:int = 0; i < 10; i++) 
			{
				var p:Person=new Person();
				p.firstName=firstNameArr[Math.floor(Math.random()*firstNameArr.length)];
				p.lastName=lastNameArr[Math.floor(Math.random()*lastNameArr.length)];
				p.age=Math.floor(Math.random()*ageMax);
				personArr[i]=p;
			}
			
			trace(personArr);
			
			personArr.sort(comparePerson);
			
			trace(personArr);
		}
		
		private function comparePersonAge(a:Person,b:Person):int
		{
			if(a.age>b.age)return 1;
			else if(a.age<b.age)return -1;
			return 0;
		}
		
		private function comparePersonFirstName(a:Person,b:Person):int
		{
			if(a.firstName>b.firstName)return 1;
			else if(a.firstName<b.firstName)return -1;
			return 0;
		}
		
		private function comparePersonLastName(a:Person,b:Person):int
		{
			if(a.lastName>b.lastName)return 1;
			else if(a.lastName<b.lastName)return -1;
			return 0;
		}
		
		private function comparePerson(a:Person,b:Person):int
		{
			var result:int=0;
			
			//这里的排序权重:即:顺序的先后,现在这里是以:FirstName为最优条件
			//当然你也可以试着换一下排序函数的顺序,即可看到效果。
			result=comparePersonFirstName(a,b);
			if(result!=0)return result;
			
			result=comparePersonLastName(a,b);
			if(result!=0)return result;
			
			result=comparePersonAge(a,b);
			if(result!=0)return result;
			
			return 0;
		}
	}
}

class Person
{
	public var lastName:String;
	
	public var firstName:String;
	
	public var age:uint;
	
	public function toString():String
	{
		return firstName+"."+lastName+" age:"+age;
	}
}


输出:

Harry.D age:43,Waston.FF age:35,Waston.EE age:136,Jave.FF age:94,John.BB age:135,Waston.CCC age:41,Bill.GG age:139,John.BB age:93,Waston.FF age:44,Jave.HH age:65
Bill.GG age:139,Harry.D age:43,Jave.FF age:94,Jave.HH age:65,John.BB age:93,John.BB age:135,Waston.CCC age:41,Waston.EE age:136,Waston.FF age:35,Waston.FF age:44


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值