日期:2014-05-16  浏览次数:20446 次

JavaScript中的中文排序问题
以下代码已经实现了英文名字的排序,但是中文名字却不能按拼音排序,怎么解决?

HTML代码:
<html>
<head>
<title> Array   Sorting   Example </title>
<script   language= "JavaScript "   type= "text/javascript "   src= "sort.js ">
</script>
</head>

<body>
<h1> Sorting   String   Arrays </h1>
<p>
Enter   two   or   more   name   in   the   field   below,   and   the   sorted   list   of   names   will   appear   in   the   text   area.
</p>

<form   name= "theform ">
Name:
<input   type= "text "   name= "newname "   size= "20 ">
<input   type= "button "   name= "addname "   value= "Add "   onclick= "SortNames(); ">
<br>
<h2> Sorted   Names </h2>
<textarea   cols   =   "60 "   rows   =   "10 "   name   =   "sorted ">
The   sorted   names   will   appear   here.
</textarea>
</form>
</body>
</html>

JS代码:

var   numnames   =   0;
var   names   =   new   Array();
var   nums   =   new   Array();
function   SortNames()
{
thename   =   document.theform.newname.value;
thename   =   thename.toUpperCase();

names[numnames]   =   thename;
nums[numnames]   =   numnames;

numnames++;

names.sort();

document.theform.sorted.value   =   names;
}

------解决方案--------------------

百渡搜一下n多

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

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

<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)});
document.getElementById( 'r2 ').value=a;
}

//-->
</script>
<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>