Introduction to the sort () method of arrays in javascript
The sort () method of the array is used for sorting. This article describes how to use the sort () method in javascript.
The Code is as follows:
<Html>
<Head>
<Title> sort () method of the array </title>
<Script>
/*
Sort ()
1. No copies are generated and the original array is directly referenced.
2. If no parameters are used when this method is called, the elements in the array are sorted alphabetically,
To be more precise, sort by character encoding.
To achieve this, first convert the elements of the array into strings (if necessary) for comparison.
3. If you want to sort by other criteria, you need to provide a comparison function. This function must compare two values,
Return a number indicating the relative sequence of the two values.
The comparison function should have two parameters, a and B. The returned values are as follows:
If a is less than B, a should appear before B in the sorted array, then a value smaller than 0 is returned.
If a is equal to B, 0 is returned.
If a is greater than B, a value greater than 0 is returned.
*/
Var arr = [2, 4, 8, 1, 2, 3];
Var arrSort = arr. sort (); // The array is not sorted correctly. The array is converted to a string and then sorted.
Document. write ("the default sorting array is:" + arrSort ); //,
Document. write ("<br/> ");
// Comparison Function
Function mysort (a, B ){
Return a-B;
}
Var arrSort2 = arr. sort (mysort); // pass in the comparison Function
Document. write ("the input comparison parameter array is:" + arrSort2); // sort the parameters correctly.
Document. write ("<br/> ");
Document. write ("the original array is:" + arr );
</Script>
</Head>
<Body>
<Div id = "time"> </div>
</Body>
</Html>