Posted in Javascript onOctober 09, 2017
本文实例讲述了JS实现中文汉字按拼音排序的方法。分享给大家供大家参考,具体如下:
代码1,拼音排序:
var array = ['武汉', '北京', '上海', '天津']; var resultArray = array.sort( function compareFunction(param1, param2) { return param1.localeCompare(param2,"zh"); } ); console.log(resultArray);
火狐浏览器 resultArray 结果为:
[ '北京' , '上海' , '天津' ,'武汉' ] ;
代码2,拼音排序并按字母分类:
function pySegSort(arr,empty) { if(!String.prototype.localeCompare) return null; var letters = "*abcdefghjklmnopqrstwxyz".split(''); var zh = "阿八嚓哒??发旮哈讥咔垃???噢?r七??P它?夕丫??".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获取中文拼音首字母,并通过拼音首字母快速查找页面内的中文内容: https://3water.com/article/90842.htm
JS实现超简单的汉字转拼音功能示例:https://3water.com/article/100864.htm
一个实现汉字与拼音互转的小巧web工具库:https://github.com/sxei/pinyinjs
JS实现中文汉字按拼音排序的方法
- Author -
为师灭了你声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@