Simple examples of the Array resort method and the operation method

  • 2020-03-30 01:25:33
  • OfStack


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title> heavy Sorting method And operation method </title>
    <script type="text/javascript">    
    //Sorting method
      function basicSort(){
         var values=[0,10,2,3,12,5];
         alert(values.reverse());//The reverse() method simply reverses the order of the array
         alert(values.sort());//The sort() method compares strings and is not the best solution in most cases
         alert(values.sort(compare));//The sort() method can take a comparison function as an argument
      }

      //Custom comparison functions that return an array in ascending order can also be changed by code, such as value1<Value2 return 1 and so on to get the result to be in descending order.
      function compare(value1,value2){
        if(value1 < value2){
          return -1;
        }else if(value1 > value2){
         return 1;
        }else{
          return 0;
        }
      }

      //The concat() method creates a new array based on all the items in the current array
      function basicConcat(){
        var colors=["red","blue","pink"];
        var colors2=colors.concat("yellow",["black","brown"]);//red,blue,pink,yellow,black,brown
        alert(colors2);
      }

      //The method is to create a new array based on all the items in the current array, which can take one or two arguments, interception & PI; End> STR> =start(that is, the end position is not included)
      function basicSlice(){
         var colors=["red","blue","pink","yello","white"];
         var colors2=colors.slice(1);
         var colors3=colors.slice(1,4);
         alert(colors2);
         alert(colors3);
      }

      function basicSplice(){
         var colors=["red","blue","pink","yello","white"];
         var removed=colors.splice(0,2);//Table deletion is the deletion of the first two items
         alert(" Deleted items: "+removed+"---- Current term: "+colors)
         var inserted=colors.splice(1,0,"black","gray");//Indicates that 0 item is deleted at position 1 and a new addition item is inserted
         alert(" Current term: "+colors);
      }

    </script>
</head>
<body>
  <input type="button" value=" The sorting Sort" onclick="basicSort();" />
  <input type="button" value="concat" onclick="basicConcat();" />
  <input type="button" value="slice" onclick="basicSlice();" />
  <input type="button" value="splice" onclick="basicSplice();" />
</body>
</html>


Related articles: