SoFunction
Updated on 2025-03-09

Deeply understand the sort sort of js array

Just put the code in less nonsense:

<body>
  <div>
  sort()Sort arrays,Not opening up new memory,Swap the original array elements
  </div>
  <div >
  1、Simple array simple sorting
  <script type="text/javascript">
    var arrSimple=new Array(1,8,7,6);
    ();
    (());
  </script>
  </div>
  <div>
  2、Simple array custom sorting
  <script type="text/javascript">
    var arrSimple2=new Array(1,8,7,6);
    (function(a,b){
      return b-a});
    (());
  </script>
  explain:a,bRepresents any two elements in the array,likereturn > 0 bforwardaback;reutrn < 0 aforwardbback;a=bBrowser compatibility exists
  Simplify it:a-bOutput sorted from small to large,b-aOutput sort from large to small。
  </div>
  <div>
  3、Simple objectListCustom attribute sorting
  <script type="text/javascript">
    var objectList = new Array();
    function Persion(name,age){
      =name;
      =age;
      }
    (new Persion('jack',20));
    (new Persion('tony',25));
    (new Persion('stone',26));
    (new Persion('mandy',23));
    //Sorted by age from childhood to adult    (function(a,b){
      return });
    for(var i=0;i<;i++){
      ('<br />age:'+objectList[i].age+' name:'+objectList[i].name);
      }
  </script>
  </div>
  <div>
  4、Simple objectListSort editable properties
  <script type="text/javascript">
    var objectList2 = new Array();
    function WorkMate(name,age){
      =name;
      var _age=age;
      =function(){
        if(!arguments)
        {
          _age=arguments[0];}
        else
        {
          return _age;}
        }
        
      }
    (new WorkMate('jack',20));
    (new WorkMate('tony',25));
    (new WorkMate('stone',26));
    (new WorkMate('mandy',23));
    //Sorted by age from childhood to adult    (function(a,b){
      return ()-();
      });
    for(var i=0;i<;i++){
      ('<br />age:'+objectList2[i].age()+' name:'+objectList2[i].name);
      }
  </script>
  </div>
</body>

The above article in-depth understanding of the sort sort of js array is all the content I share with you. I hope you can give you a reference and I hope you can support me more.