| <Script> Function SortNumber (obj, func) // defines a general sorting function { // Parameter verification. If the first parameter is not an array or the second parameter is not a function, an exception is thrown. If (! (Obj instanceof Array) |! (Func instanceof Function )) { Var e = new Error (); // generate Error message E. number = 100000; // defines the error number E. message = "invalid parameter"; // error description Throw e; // throw an exception } For (n in obj) // start sorting { For (m in obj) { If (func (obj [n], obj [m]) // use the callback function for sorting. The rules are set by the user. { Var tmp = obj [n]; // create a temporary variable Obj [n] = obj [m]; // exchange data Obj [m] = tmp; } } } Return obj; // return the sorted Array } Function greatThan (arg1, arg2) // callback function, user-defined sorting rule { Return arg1 <arg2; } Try { Var numAry = new Array (, 9); // generates an Array Document. write ("<li> before sorting:" + numAry); // output the array before sorting. SortNumber (numAry, greatThan); // call the sorting Function Document. write ("<li> after sorting:" + numAry); // output the sorted Array } Catch (e) { Alert (e. number + ":" + e. message ); } </Script> |