Now in learning JavaScript, finding the sort () function is a bit of a strange thing (maybe it's my level problem-_-! , so just record what you found here. Sort () The parameter of this method is very strange, it must be a function, but also an optional parameter, if there are no parameters, it will default in the dictionary order of strings (even if the value is converted to a string to handle). This parameter is to be able to compare the size of two values, such as:
function Sortnumber (A, b) {
return a-B; The return is their difference, if the value is less than 0, will be a row in front, if greater than 0, will be b in front, if it is 0, just casually. (Bubble Sort Method!!) )
}
The application is as follows (this example is too classic!!) ):
<script type= "Text/javascript" >
function Sortnumber (A, A,) {return a-B}
var arr = new Array (3)
Arr[0] = "10";
ARR[1] = "5";
ARR[2] = "4";
document.write (arr + "<br/>");
document.write ( arr.sort(sortNumber)
);
</script>
Then the arrangement of the original 10,5,4 will become 4,5,10. Here is a description of the process, obviously sortnumber should have two parameters, but we call when a parameter is not, how to compare ah? Here is the case when Arr calls sort from the first number, 10 is no number compared to it, so the second, that is 5, then 10 will be compared with 5, so it will call Sortnumber and 10 and 5 in, this is the character of sort ().
The sort () method in JavaScript