<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title>Example 6-3</title></Head><Body><Scriptlanguage= "JavaScript"> functionsortnumber (obj, func)//defining a universal sort function { //parameter validation, throws an exception if the first parameter is not an array or the second argument is not a function if( !(objinstanceofArray)|| !(funcinstanceofFunction)) { vare= NewError (); //Generate error messageE.number= 100000; //define the error numberE.message= "Invalid parameter"; //Error Description Throwe; //Throw Exception } for(ninchobj)//Start Sorting { for(Minchobj) { if(func (Obj[n], obj[m]))//use callback functions to sort the rules set by the user { vartmp=Obj[n]; Obj[n]=Obj[m]; OBJ[M]=tmp; } } } returnobj; //returns the sorted array } functionGreatthan (arg1, arg2)//callback function, user-defined collation { returnarg1>arg2; //rules: From big to small } Try { varnumary= NewArray (5,8,6, +,1, $,7, - ); //generate an arraydocument.write ("<li> before sorting:"+numary); //data before the output is sortedSortnumber (numary, Greatthan)//Call sort functiondocument.write ("<li> after sorting:"+numary); //output sorted Array } Catch(e) {alert (E.number+":"+e.message); //Exception Handling }</Script></Body></HTML>
callback function, user-defined collation