<script>
function Sortnumber (OBJ,FUNC)//define General sort function
{
Parameter validation, throws an exception if the first parameter is not an array or the second argument is not a function
if (! ( obj instanceof Array) | | ! (func instanceof Function))
{
var e = new Error (); Generate error message
E.number = 100000; Define the error number
E.message = "Invalid parameter"; Error description
Throw e; Throw exception
}
for (n in obj)//start sort
{
for (m in obj)
{
if (func (Obj[n],obj[m]))//Sort using callback function, the rule is set by the user
{
var tmp = Obj[n]; Create a temporary variable
Obj[n] = obj[m]; Exchanging data
OBJ[M] = tmp;
}
}
}
return obj; Returns the sorted array
}
function Greatthan (ARG1,ARG2)//callback function, user-defined collation
{
return Arg1 < arg2;
}
Try
{
var numary = new Array (5,8,6,32,1,45,6,89,9); Generate an array
document.write ("<li> before sorting:" +numary); Array before the output is sorted
Sortnumber (Numary,greatthan); Call sort function
document.write ("<li> after sorting:" +numary); Output sorted Array
}
catch (E)
{
Alert (e.number+ ":" +e.message);
}
</script>
The
writes a sort function to sort the numbers. The sorting method is implemented by the client function, the number of function parameters is two, the relationship of two parameters is the relationship between the sorted elements.