欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascript 排序

程序员文章站 2022-04-19 09:56:15
...

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>

 如果有错误,请指出~