首页 > 代码库 > js-sort数组排序

js-sort数组排序

婆婆妈妈,直上代码:

 

 1 <body>
 2 <div>
 3 sort()对数组排序,不开辟新的内存,对原有数组元素进行调换
 4 </div>
 5 <div id="showBox">
 6 1、简单数组简单排序
 7 <script type="text/javascript">
 8 var arrSimple=new Array(1,8,7,6);
 9 arrSimple.sort();
10 document.writeln(arrSimple.join());
11 </script>
12 </div>
13 <div>
14 2、简单数组自定义排序
15 <script type="text/javascript">
16 var arrSimple2=new Array(1,8,7,6);
17 arrSimple2.sort(function(a,b){
18 return b-a});
19 document.writeln(arrSimple2.join());
20 </script>
21 解释:a,b表示数组中的任意两个元素,若return > 0 b前a后;reutrn < 0 a前b后;a=b时存在浏览器兼容
22 简化一下:a-b输出从小到大排序,b-a输出从大到小排序。
23 </div>
24 <div>
25 3、简单对象List自定义属性排序
26 <script type="text/javascript">
27 var objectList = new Array();
28 function Persion(name,age){
29 this.name=name;
30 this.age=age;
31 }
32 objectList.push(new Persion(jack,20));
33 objectList.push(new Persion(tony,25));
34 objectList.push(new Persion(stone,26));
35 objectList.push(new Persion(mandy,23));
36 //按年龄从小到大排序
37 objectList.sort(function(a,b){
38 return a.age-b.age});
39 for(var i=0;i<objectList.length;i++){
40 document.writeln(<br />age:+objectList[i].age+ name:+objectList[i].name);
41 }
42 </script>
43 </div>
44 <div>
45 4、简单对象List对可编辑属性的排序
46 <script type="text/javascript">
47 var objectList2 = new Array();
48 function WorkMate(name,age){
49 this.name=name;
50 var _age=age;
51 this.age=function(){
52 if(!arguments)
53 {
54 _age=arguments[0];}
55 else
56 {
57 return _age;}
58 }
59 
60 }
61 objectList2.push(new WorkMate(jack,20));
62 objectList2.push(new WorkMate(tony,25));
63 objectList2.push(new WorkMate(stone,26));
64 objectList2.push(new WorkMate(mandy,23));
65 //按年龄从小到大排序
66 objectList2.sort(function(a,b){
67 return a.age()-b.age();
68 });
69 for(var i=0;i<objectList2.length;i++){
70 document.writeln(<br />age:+objectList2[i].age()+ name:+objectList2[i].name);
71 }
72 </script>
73 </div>
74 </body>

 

js-sort数组排序