1. Sorting:
The default sort () is sorted by character encoding:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
<! --
Var testArray = [3,324,534, 665,];
TestArray. sort ();
Alert (testArray );
// -->
</Script>
Now we want to sort it by numerical value:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
<! --
Var testArray = [3,324,534, 665,];
TestArray. sort (function (a, B) {return a-B ;});
Alert (testArray );
// -->
</Script>
You only need to pass a comparison function to sort. If the value of the comparison function is smaller than 0, it means that a must appear before B; otherwise, a must follow B.
2. disordered order:
Let the comparison function randomly return-1 or 1:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
<! --
Var testArray = [,];
TestArray. sort (function () {return Math. random ()> 0.5? -1:1 ;});
Alert (testArray );
// -->
</Script>
3. Search:
It's quite fresh to use sort () for searching. Let's see how it works.
Now I want to find out all the elements in the array containing the letter 'A'. If there is no sort (), it seems that I can only use traversal. The traversal efficiency... That's horrible !! The procedure is as follows:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
<! --
Var testArray = ['df ', 'rtr', 'wy', 'daf', 'dfs', 'wefa ', 'tyr', 'rty', 'rty ', 'ryt', 'afds ', 'huer', 'te'];
TestArray. sort (function (a, B) {return a. indexOf ('A') =-1? 1:-1 ;});
Alert (testArray );
// -->
</Script>
In this way, all the elements in the array containing the letter 'A' are placed in front of the array. After some simple processing, the search results can be output.
The above are the three methods I have summarized to use sort () to operate arrays in javascript. If you are interested, you will find that sort () has many advantages ......