源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JS实现中文汉字按拼音排序的方法

  • 时间:2020-11-14 02:01 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JS实现中文汉字按拼音排序的方法
本文实例讲述了JS实现中文汉字按拼音排序的方法。分享给大家供大家参考,具体如下: [b]代码1,拼音排序:[/b]
var array = ['武汉', '北京', '上海', '天津'];
var resultArray = array.sort(
 function compareFunction(param1, param2) {
  return param1.localeCompare(param2,"zh");
 }
);
console.log(resultArray);

火狐浏览器 resultArray 结果为:
[ '北京' , '上海' , '天津' ,'武汉' ] ;
[b]代码2,拼音排序并按字母分类:[/b]
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":["呀","已"]}
]"

[b]扩展:[/b] JS获取中文拼音首字母,并通过拼音首字母快速查找页面内的中文内容: [url=http://www.1sucai.cn/article/90842.htm]http://www.1sucai.cn/article/90842.htm[/url] JS实现超简单的汉字转拼音功能示例:[url=http://www.1sucai.cn/article/100864.htm]http://www.1sucai.cn/article/100864.htm[/url] 一个实现汉字与拼音互转的小巧web工具库:[url=https://github.com/sxei/pinyinjs]https://github.com/sxei/pinyinjs[/url] [b]PS:这里再为大家推荐2款比较实用的相关在线排序工具供大家参考使用:[/b] [b]在线中英文根据首字母排序工具: [/b][url=http://tools.jb51.net/aideddesign/zh_paixu]http://tools.jb51.net/aideddesign/zh_paixu[/url] [b]在线文本倒序翻转排序工具: [/b][url=http://tools.jb51.net/aideddesign/flipped_txt]http://tools.jb51.net/aideddesign/flipped_txt[/url] 更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/472.htm]JavaScript查找算法技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/281.htm]JavaScript遍历算法与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/781.htm]JavaScript传值操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/751.htm]javascript编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/313.htm]JavaScript中json操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/502.htm]JavaScript切换特效与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/462.htm]JavaScript动画特效与技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/439.htm]JavaScript错误与调试技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/297.htm]JavaScript数据结构与算法技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/119.htm]JavaScript数学运算用法总结[/url]》 希望本文所述对大家JavaScript程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部