js中文漢字按拼音排序


JavaScript 提供本地化文字排序,比如對中文按照拼音排序,不需要程序顯示比較字符串拼音。

String.prototype.localeCompare 在不考慮多音字的前提下,基本可以完美實現按照拼音排序。

在沒有出現意外的情況下,各個支持 localeCompare 的瀏覽器都很正常。最近將 Chrome 更新到 58.0.3029.110,突然發現中文排序不正常。

確認之后是 localeCompare 需要明確指定 locales 參數.

 

代碼1,拼音排序:

復制代碼
var array = ['武漢', '北京', '上海', '天津'];
var resultArray = array.sort(
    function compareFunction(param1, param2) {
        return param1.localeCompare(param2,"zh");
    }
);
console.log(resultArray);
復制代碼

火狐瀏覽器 resultArray 結果為:[ '北京' , '上海' , '天津' ,'武漢' ] ;

 

代碼2,拼音排序並按字母分類:

復制代碼
 1 function pySegSort(arr,empty) {
 2     if(!String.prototype.localeCompare)
 3         return null;
 4      
 5     var letters = "*abcdefghjklmnopqrstwxyz".split('');
 6     var zh = "阿八嚓噠妸發旮哈譏咔垃痳拏噢妑七呥扨它穵夕丫帀".split('');
 7      
 8     var segs = [];
 9     var curr;
10     $.each(letters, function(i){
11         curr = {letter: this, data:[]};
12         $.each(arr, function() {
13             if((!zh[i-1] || zh[i-1].localeCompare(this,"zh") <= 0) && this.localeCompare(zh[i],"zh") == -1) {
14                 curr.data.push(this);
15             }
16         });
17         if(empty || curr.data.length) {
18             segs.push(curr);
19             curr.data.sort(function(a,b){
20                 return a.localeCompare(b,"zh");
21             });
22         }
23     });
24     return segs;
25 }
復制代碼

 

JSON.stringify(pySegSort([ "我" , "不" , "懂" , "愛" , "啊" , "按" , "已" , "呀" , "選" , "縣" ]))
//結果
"[
  {" letter ":" a "," data ":[" "," "," "]} ,
  {" letter ":" b "," data ":[" "]} ,
  {" letter ":" d "," data ":[" "]} ,
  {" letter ":" w "," data ":[" "]},
  {" letter ":" x "," data ":[" "," "]},
  {" letter ":" y "," data ":[" "," "]}
]"
 
 
擴展:http://blog.csdn.net/testcs_dn/article/details/25116655         ------JS獲取中文拼音首字母,並通過拼音首字母快速查找頁面內的中文內容
           http://www.jb51.net/article/100864.htm      ----------JS實現超簡單的漢字轉拼音功能示例
           https://github.com/sxei/pinyinjs                  -----------一個實現漢字與拼音互轉的小巧web工具庫


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM