本文主要介紹了JS實現中文漢字按拼音排序的方法,涉及javascript針對中文字符串的轉換、遍歷、排序等相關操作技巧,需要的朋友可以參考下,希望能幫助到大家。
程式碼1,拼音排序:
var array = ['武汉', '北京', '上海', '天津']; var resultArray = array.sort( function compareFunction(param1, param2) { return param1.localeCompare(param2,"zh"); } ); console.log(resultArray);
火狐瀏覽器resultArray 結果為:
[ '北京' , '上海' , '天津' ,'武汉' ] ;
function pySegSort(arr,empty) { if(!String.prototype.localeCompare) return null; var letters = "*abcdefghjklmnopqrstwxyz".split(''); var zh = "阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀".split(''); var segs = []; var curr; $.each(letters, function(i){ curr = {letter: this, data:[]}; $.each(arr, function() { if((!zh[i-1] || zh[i-1].localeCompare(this,"zh") <= 0) && this.localeCompare(zh[i],"zh") == -1) { curr.data.push(this); } }); if(empty || curr.data.length) { segs.push(curr); curr.data.sort(function(a,b){ return a.localeCompare(b,"zh"); }); } }); return segs; } JSON.stringify(pySegSort(["我","不","懂","爱","啊","按","已","呀","选","县"]))
"[ {"letter":"a","data":["啊","爱","按"]}, {"letter":"b","data":["不"]}, {"letter":"d","data":["懂"]}, {"letter":"w","data":["我"]}, {"letter":"x","data":["县","选"]}, {"letter":"y","data":["呀","已"]} ]"
以上是JS實作漢字按拼音排序的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!