配列の並べ替えの簡単な方法(回転)

2607 ワード

最近はいくつかのタイプの問題をする時、配列順が出てきました.http://www.cnblogs.com/longze/archive/2012/11/27/2791230.html)で簡単な配列の並べ替え方法を学び、ちょっとした修正を行いました.

    
sort() , ,
1、 var arrSimple=new Array(1,8,7,6); arrSimple.sort(); document.writeln(arrSimple.join());
2、 var arrSimple2=new Array(1,8,7,6); arrSimple2.sort(function(a,b){ return b-a}); document.writeln(arrSimple2.join()); :a,b , return > 0 b a ;reutrn < 0 a b ;a=b :a-b ,b-a 。
3、 List 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); }
4、 List 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++){ document.writeln('<br />age:'+objectList2[i].age()+' name:'+objectList2[i].name); }
第二の方法は、並べ替えられた数字タイプの場合は、直接減算すればいいです.並べ替えられた文字列タイプの場合は、localeCompareメソッドを使用する必要があります.
例:return(b.sort+").localeComppare((a.sort+");