码迷,mamicode.com
首页 > 编程语言 > 详细

JS 用sort方法排序字符串

时间:2015-04-10 15:29:17      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

JavaScript提供了一种更简便的方法用于比较两个字符串——localeCompare(),localeCompare()使用本地特定的顺序来比较两个字符串,语法如下:
string.localeCompare(target)
参数target是要与string进行比较的字符串。
如果string小于target,则localeCompare()返回小于0的数;
如果string大于target,返回大于0的数;
如果相等(或按照本地顺序的约定两者顺序相当),则返回0。
利用该方法替换上面冗长的作法后,除了代码减少了之外,运行速度也快了不少,而且还支持其它字符库的本地排序。
修改后代码如下:

<html>
<head>
<title>汉字排序</title>
<script type=”text/javascript”>
<!–
 function startSort(){
  var a=document.getElementById(‘s’).value;
  a=a.split(‘,’)
  a.sort();
  document.getElementById(‘r1′).value=a;
  a.sort(function(a,b){return a.localeCompare(b)}); //正序排列 a.sort(function(a,b){return b.localeCompare(a)}); //反序排列

  document.getElementById(‘r2′).value=a;
 }
  
//–>
</script>
</head>

<body>
<p>包含汉字的字符串数组(用逗号”,”隔开):<br />
<textarea id=”s” style=”width: 100%; overflow: scroll; word-wrap: normal;” rows=”10″>张韶涵,b土,abort,张学友,something,苹果,五月天,刘德华,香蕉,apple,范玮琪,阿桑</textarea></p>

<p style=”text-align: center”><input type=”button” value=”排序测试” onclick=”startSort()” style=”width: 300px” /></p>

<p>默认排序结果:<br />
<textarea id=”r1″ style=”width: 100%; overflow: scroll; word-wrap: normal;” rows=”10″></textarea></p>

<p>汉字拼音顺序排序结果:<br />
<textarea id=”r2″ style=”width: 100%; overflow: scroll; word-wrap: normal;” rows=”10″></textarea></p>

</body>
</html>

该方法目前已作为ECMAScript v3标准,在支持JavaScript 1.5(Mozilla、Netscape 6+)以及JScript 5.5(IE 5.5+)的浏览器中均得到了支持。

JS 用sort方法排序字符串

标签:

原文地址:http://www.cnblogs.com/sunshq/p/4414512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!