sort()的使用
1 簡單數(shù)組簡單排序
<script type="text/javascript"> var arr=new Array(1,8,7,6); arr.sort(); console.log(arr);//[ 1, 6, 7, 8 ] </script>
2 簡單數(shù)組自定義排序
<script type="text/javascript"> var arr=new Array(1,8,7,6); arr.sort(function(a,b){return b-a}); console.log(arr);//[ 8, 7, 6, 1 ] </script> //a,b表示數(shù)組中的任意兩個元素,a-b輸出從小到大排序,b-a輸出從大到小排序。(若return > 0 b前a后;reutrn < 0 a前b后;a=b時存在瀏覽器兼容簡化一下:)
3 簡單對象List自定義屬性排序
<script type="text/javascript"> var objectList = new Array(); function Persion(name,age){ this.name=name; this.age=age; } objectList.push(new Persion('jack',20)); objectList.push(new Persion('tony',25)); objectList.push(new Persion('stone',26)); objectList.push(new Persion('mandy',23)); //按年齡從小到大排序 objectList.sort(function(a,b){ return a.age-b.age}); for(var i=0;i<objectList.length;i++){ document.writeln('<br />age:'+objectList[i].age+' name:'+objectList[i].name); } </script>
4 簡單對象List對可編輯屬性的排序
<script type="text/javascript"> var objectList2 = new Array(); function WorkMate(name,age){ this.name=name; var _age=age; this.age=function(){ if(!arguments) { _age=arguments[0]; }else { return _age; }} } objectList2.push(new WorkMate('jack',20)); objectList2.push(new WorkMate('tony',25)); objectList2.push(new WorkMate('stone',26)); objectList2.push(new WorkMate('mandy',23)); //按年齡從小到大排序 objectList2.sort(function(a,b){return a.age()-b.age(); }); for(var i=0;i<objectList2.length;i++){ console.log(objectList2[i].name+':'+objectList2[i].age()+';'); } </script>