javascript sort () of elements in the array are sorted

javascript sort () can sort elements in the array,

Syntax: arrayObject.sort (sortby)

arrayObject is an array of objects, SortBy is optional, it is used to determine the order of elements of the name of the function, if it is omitted, the elements are arranged in the ascending sequence of ASCII characters.

Comparison function when not in use to sort, sort methods are ordered by ASCII value of the character, starting with the first character of the comparison, if the first character is equal, then compare the second characters, and so on.

For numeric data, if the comparison in accordance with the character, the result might not be what we want, and therefore needs the comparison function. Comparison function has two parameters, representing two array entries when each sort. sort () compares two array entries will be executed this parameter when sorting and comparing the two array items passed as a parameter to the function. When the function returns a value greater than 0 on the order of two switching arrays, or not switched, i.e., the function returns a value less than 0, represents the ascending order, the function returns a value greater than 0, represents the descending order.

<! DOCTYPE HTML> 
<HTML> 
<head> 
    <title> in the array elements are sorted </ title> 
    <Meta HTTP-equiv = "the Content-the Type" Content = "text / HTML; charset = UTF-. 8"> 
    <Script type = "text / JavaScript"> 
        var X = new new the array (1,20,8,12,6,7); // creates an array 
        document.write ( "Sort front array:" + x.join ( ", ") +" <p> " ); // output array element 
        x.sort (); // ascending order by character array 
        document.write (" do not use the sorted array comparison function: "+ x.join (", " ) + "<p>") ; // output after the array is sorted 
        x.sort (asc); // comparison function has ascending 
        / * ascending comparison function * / 
        function ASC (a, B) { 
            return ab &; 
        } 
        Document .write ( " 
        function des (A, B) {After Ascending array: "+ x.join (", " ) +" <p> "); // output array after sorting 
        x.sort (des); // with a descending function of the comparison
        / * Descending function * / 
            return BA; 
        } 
        document.write ( "Sort Descending the array:" + x.join ( "," )); // the output array is sorted 
 </ Script> 
</ head> 
<body> 
</ body> 
</ HTML>

  

Guess you like

Origin www.cnblogs.com/rjbc/p/11666324.html