Home > Article > Web Front-end > JavaScript example code for sorting Chinese characters_javascript skills
For example, var arr = ["中","华","人","民","Communist","和","国"], after executing the sort method, the result is: China, People, Communist Party, China, He, Guo, Min, are neither pinyin nor the order of the number of strokes.
I have rarely paid attention to the localeCompare method before. The manual says that it returns a value when executed, indicating whether the two strings are the same in the current locale. There are three types of return values: -1, 0, 1, which are exactly the types required by the sort method parameters. Apply localeCompare to the sort method and see the result:
var arr = ["中","华","人","民","公","和","国" ];
alert(arr.sort(function(a,b){return a.localeCompare(b)}));//The result is: Communist, Guo, He, Hua, Min, Ren, Zhong (pinyin ascending order )
Note that the localeCompare method compares in the current area, that is, the comparison environment is the geographical area set by the current operating system, such as the representation of numbers, currency, date and time, etc. (in the "Control Panel" You can check and modify in ), if the sorting method is set to stroke, the above result will be: People, China, People's Republic of China, Communist Party, China, and Country (in ascending order of strokes).