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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM