深入理解js數組的sort排序_javascript技巧

來源:互聯網
上載者:User

廢話少說直接上代碼:

<body>  <div>  sort()對數組排序,不開闢新的記憶體,對原有數組元素進行調換  </div>  <div id="showBox">  1、簡單數組簡單排序  <script type="text/javascript">    var arrSimple=new Array(1,8,7,6);    arrSimple.sort();    document.writeln(arrSimple.join());  </script>  </div>  <div>  2、簡單數組自訂排序  <script type="text/javascript">    var arrSimple2=new Array(1,8,7,6);    arrSimple2.sort(function(a,b){      return b-a});    document.writeln(arrSimple2.join());  </script>  解釋:a,b表示數組中的任意兩個元素,若return > 0 b前a後;reutrn < 0 a前b後;a=b時存在瀏覽器安全色  簡化一下:a-b輸出從小到大排序,b-a輸出從大到小排序。  </div>  <div>  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>  </div>  <div>  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++){      document.writeln('<br />age:'+objectList2[i].age()+' name:'+objectList2[i].name);      }  </script>  </div></body>

以上這篇深入理解js數組的sort排序就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.