Js simulates the sort method of Array. The Array object of JavaScript has an sort method to sort Array elements. This method is sorted in ascending order by the ASCII characters of Array items by default.
For example, [6, 7, 9, 1,-1]. sort (); after execution, the array is changed to [-, 6, 7, 9].
This method cannot be executed well if you need to sort the strings in descending order or not.
Of course, sort has an optional parameter, which can help us solve this problem. By passing in a function for sort, sort sorts the returned values of the function.
Array: This function is used to pass in two elements in the array by default. For example, if a and B are passed in, if the return value of the function is greater than 0, the sorting method is B and a. If the return value is less than 0, the sorting result is a and B.
The specific meaning is hard to explain. I didn't understand how the sort was sorted at the beginning.
If you know the implementation process, the sorting principle is clear.
The implementation of sort is actually a simple Bubble sorting.
I even simulated it today. You must understand the sort principle when you understand this function.
<Script type = "text/javascript"> <! -- Var myarray = new Array (, 1,-); var myarray1 = new Array (, 1,-); var sortAsc = function (x, y) {return x-y ;}; var sortDesc = function (x, y) {return y-x ;}; Array. prototype. st = function (fn) {var t; fn = fn | function (x, y) {return x-y}; for (var I = 0; I <this. length; I ++) {for (var j = I; j <this. length; j ++) {if (fn (this [I], this [j])> 0) {t = this [I]; this [I] = this [j]; this [j] = t ;}}} myarray. st (); alert ("Default Ascending Order:" + myarray); myarray. st (sortDesc); alert ("sort in descending order:" + myarray); myarray. st (sortAsc); alert ("Ascending Order:" + myarray); myarray1.sort (function () {return 1}); // note: js's default sort is different from this sorting result. Its sorting method does not understand alert ("reverse sorting:" + myarray1); // --> script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]