javascript 排序

javascript的原生态的sort排序功能不够强大,项目中运用到,晚上查阅资料,与大家共享。

 

功能需求:利用JavaScript进行对象排序,例如根据用户的年龄排序展示,数据如下:

<script type="text/javascript">
         	 function Player(name,age){
         	 	this.name = name;
         	 	this.age = age;
         	 }
         	 
         	 var Lyn = new Player("Lyncc",25);
         	 var Fly = new Player("Fly",27);
         	 var Sky = new Player("Sky",29);
         	 var Miss = new Player("Miss",24);
         	 
         	 var war3Players = [Lyn,Fly,Sky,Miss];
</script>

 根据JavaScript的策略模式和js的闭包:

<script type="text/javascript">
         	 function Player(name,age){
         	 	this.name = name;
         	 	this.age = age;
         	 }
         	 
         	 var Lyn = new Player("Lyncc",25);
         	 var Fly = new Player("Fly",27);
         	 var Sky = new Player("Sky",29);
         	 var Miss = new Player("Miss",24);
         	 
         	 var war3Players = [Lyn,Fly,Sky,Miss];
         	 
         	 war3Players.sort(sortByValue("age"));
         	 for(var p in war3Players){
           	 console.info(war3Players[p].name+war3Players[p].age);
             }
             
             function sortByValue(value){
             	var realSort = function(obj1,obj2){
             		if(obj1[value]>obj2[value])return 1;
             		else if(obj1[value]==obj2[value]) return 0;
             		else return -1; 
             	};
             	return realSort;
             }
         </script>

 如果有错误,请指出~

你可能感兴趣的:(闭包,策略模式,js对象排序)