JavaScript array.sort()
The JavaScript array.sort() method can be used to reorder the array elements in JavaScript Array and return a new sorted array. Generally speaking, it can be divided into reordering English letters or words or rearranging numeric elements. And the sort method only reorders the original array, and does not generate a new array, which means that the returned result array is the original array. The JavaScript array.sort method is a built-in function and does not require additional It can be called after installation, and almost all major browsers support the JavaScript array.sort method.
JavaScript array.sort() basic syntax
array.sort( sort function or method)
Just add sort after the Array you want to process. As for the "sort function or method" in parentheses, it is an optional item to specify the sorting method. If it is not used, it can be left blank, but Normally, when sorting numbers, a condition is added to make the numbers compare to the size, otherwise the JavaScript sort function will sort by the code of the initial letter.
JavaScript array.sort() Example 1: Sort English letters and English words
var Arr = ['Father','Mother','Brother'];
document.write('Before sorting:'+Arr+'<br>');
NewArr = Arr.sort () ;
document.write('After sorting:'+NewArr);
</script>

first time document.write outputs the original array that is not sorted, and then only reorders Arr through the JavaScript sort function, returns NewArr to us, and then outputs completely different results through document.write . Here we can clearly see that the sort function takes out the first letter of the array element for comparison. This part is not a problem, but if the array elements are all numbers, what will be the result?
JavaScript array.sort() example two, sort numbers
var Arr = ['50','300','800'];
document.write('Raw array sorting:'+Arr+'<br>');
NewArr=Arr. sort(); document.write('After first sorting:'+NewArr+'<br>');
function sortFunction(x,y){return xy;}
NewArr=Arr.sort( sortFunction );
document.write( 'After the second sort:'+NewArr);
</script>

is a little more complicated like this example, because the JavaScript sort function will only take out the initial letters or characters for encoding and sorting by default. When encountering numbers, the same processing method is used, so in this example, we Two different sorting methods are prepared. The first sorting is based on the original operating principle of sort. The result of the sorting has nothing to do with the size of the number. In order to create the effect of number ratio, we prepared another sortFunction. Use it for the sort function (please pay attention to the red mark). This technique can compare the numbers in the array elements and rearrange them, so the result of the second sorting will be based on the number. !
Post a Comment
0 Comments