The sort () method is calculated according to the JavaScript manual, and the result
<script> var arr = [2,3,56,12,546,77,98]; Alert (Arr.sort ());</script>
Based on the JavaScript manual, the sort () method is calculated with the following results:
650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>650 "this.width=650;" src= "http ://s5.51cto.com/wyfs02/m02/88/ef/wkiol1gbuwna2dzmaaauybtebl4779.png-wh_500x0-wm_3-wmp_4-s_431578697.png "title= "QQ picture 20161015130502.png" alt= "Wkiol1gbuwna2dzmaaauybtebl4779.png-wh_50"/>
Can see that this is not the sort we need, so according to the manual tip:
If you provide a function for the sortfunction parameter, the function must return one of the following values:
A negative value, if the first argument passed is smaller than the second one.
0, if two parameters are equal.
Positive value if the first argument is larger than the second argument.
So I encapsulate a function demosort ()
<script> var arr = [2,3,56,12,546,77,98]; Arr.sort (Function demosort (x, y) { if (x< y) { return -1; //less than, returns -1 } else if (X > y) { return 1; // Greater than return 1 } else { //others, return 0 return 0; } }); alert (arr);</script>
In this case, the sort () function is passed again to achieve the correct ordering.
The results are as follows:
650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>650 "this.width=650;" src= "http ://s2.51cto.com/wyfs02/m01/88/f2/wkiom1gbuyqd7wpqaaacweqp-ri739.png-wh_500x0-wm_3-wmp_4-s_3091154770.png "title = "QQ picture 20161015130701.png" alt= "Wkiom1gbuyqd7wpqaaacweqp-ri739.png-wh_50"/>
In this way, the real sort is realized. As for reverse order, you can reverse the return value, or use the reverse () function directly.
This article is from the "Hello I am Forest" blog, please make sure to keep this source http://chensenlin.blog.51cto.com/10559465/1862152
JavaScript sorting issues