欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

深入理解js數(shù)組的sort排序

 更新時間:2016年05月28日 16:41:02   投稿:jingxian  
下面小編就為大家?guī)硪黄钊肜斫鈐s數(shù)組的sort排序。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

廢話少說直接上代碼:

<body>
  <div>
  sort()對數(shù)組排序,不開辟新的內(nèi)存,對原有數(shù)組元素進行調(diào)換
  </div>
  <div id="showBox">
  1、簡單數(shù)組簡單排序
  <script type="text/javascript">
    var arrSimple=new Array(1,8,7,6);
    arrSimple.sort();
    document.writeln(arrSimple.join());
  </script>
  </div>
  <div>
  2、簡單數(shù)組自定義排序
  <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表示數(shù)組中的任意兩個元素,若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數(shù)組的sort排序就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論