The javascript sort function implements digital sorting
- 2020-06-22 23:50:29
- OfStack
The javascript sorting function implements digital sorting
<script>
function SortNumber(obj,func) // Define a generic sorting function
{
// Parameter validation, if the 1 Parameter is not an array or a control 2 An exception is thrown when an argument is not a function
if(!(obj instanceof Array) || !(func instanceof Function))
{
var e = new Error(); // Generate error message
e.number = 100000; // Define error number
e.message = " Parameter is invalid "; // Error description
throw e; // An exception is thrown
}
for(n in obj) // Start sorting
{
for(m in obj)
{
if(func( obj[n],obj[m]) ) // Sort using callback functions, rules set by the user
{
var tmp = obj[n]; // Create temporary variables
obj[n] = obj[m]; // Exchange 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 1 An array of
document.write("<li> Before ordering :"+numAry); // Output the array before sorting
SortNumber(numAry,greatThan); // Call the sort function
document.write("<li> After the order: "+numAry); // Output the sorted array
}
catch(e)
{
alert(e.number+":"+e.message);
}
</script>
This is the end of this article, I hope you enjoy it.