javascript中文排序 |
? 原文來自:風微柳細 原來的方法是用個大中文字數組,一個個比較,:(
以下為引用內容:
更新[2005.10.06]: 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>
<p>漢字拼音順序排序結果:<br />
<textarea id="r2" style="width: 100%; overflow: scroll; word-wrap: normal;" rows="10"></textarea></p>
posted on 2006-12-19 14:39
壞男孩 閱讀(2315)
評論(1) 編輯 收藏 所屬分類:
java命令學習