javascript 中文排序

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用localeCompare實現中文排序</title>
<script language="javascript" type="text/javascript">
var a="aa,cc,bb,dd,啊啊,層次,寶貝,低調";
function defaultSort(){
    b=a.split(",");
    b.sort();
    document.getElementById("out1").innerHTML="默認排序的結果:"+b;
}
function cusSort(){
    c=a.split(",");
    c.sort(function(e,f){
      return e.localeCompare(f);
    });
    document.getElementById("out2").innerHTML="拼音排序的結果:"+c;
}
</script>
</head>
<body>
<a href="javascript:void(0);" οnclick="defaultSort();">默認排序</a><br>
<a href="javascript:void(0);" οnclick="cusSort();">拼音排序</a>


原字符串:
"aa,cc,bb,dd,啊啊,層次,寶貝,低調";


排序後:
<div id="out1"></div>
<div id="out2"></div>



<pre>
PS:
JavaScript中localeCompare函數方法是返回一個值,指出在當前的區域設置中兩個字符串是否相同。使用方法:
stringVar.localeCompare(stringExp)
其中stringVar是必選項。一個 String 對象後文字。
stringExp是必選項。將與 stringVar 進行比較的字符串。

localeCompare 可以對 stringVar 和 stringExp 進行一個區分區域設置的字符串比較並返回 –1、0 或 +1,
這取決於系統中缺省區域設置的排序。如果 stringVar 排序在 stringExp 之前,那麼 localeCompare 返回 –1;
如果 stringVar 排序在 stringExp 之後,則返回 +1。如果返回值爲 0,那就說明這兩個字符串是相同的。
</pre>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章