SoFunction
Updated on 2025-03-03

Simple examples of Array reordering methods and operation methods


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/">
<html xmlns="http:///1999/xhtml" >
<head>
<title>Reorder method and operation method</title>
    <script type="text/javascript">   
//Sorting method
      function basicSort(){
         var values=[0,10,2,3,12,5];
alert(());//reverse() method just reverses the order of the arrays
alert(());//sort() method compares strings, and most cases are not the best solution
alert((compare));//sort() method can receive a comparison function as a parameter
      }

//Customize the comparison function, the returned array is in ascending order, and you can also achieve the result in descending order by changing the code, such as value1<value2 return 1, etc.
      function compare(value1,value2){
        if(value1 < value2){
          return -1;
        }else if(value1 > value2){
         return 1;
        }else{
          return 0;
        }
      }

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

//The method is to create a new array based on all items in the current array, which can receive one or two parameters, that is, intercept end > str >=start (that is, the items that do not include the end position)
      function basicSlice(){
         var colors=["red","blue","pink","yello","white"];
         var colors2=(1);
         var colors3=(1,4);
         alert(colors2);
         alert(colors3);
      }

      function basicSplice(){
         var colors=["red","blue","pink","yello","white"];
var removed=(0,2);//Table delete means deleting the first two items
alert("Deleted item: "+removed+"----The current item: "+colors)
var inserted=(1,0,"black","gray");// means that 0 items are deleted at position 1 and new additions are inserted
alert("now item:"+colors);
      }

    </script>
</head>
<body>
<input type="button" value="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>