DIV CSS 佈局教程網

用 JavaScript 實現中文漢字依拼音排序
編輯:關於JavaScript     

要對中文進行排序,直接呼叫 sort() 往往得不到拼音順序的結果。本文示範如何透過 localeCompare 讓中文字串依漢語拼音正確排序,並和瀏覽器的預設排序做對照。

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

關鍵就在於把 a.sort() 換成 a.sort(function(a,b){return a.localeCompare(b)})。localeCompare 會依據地區語言規則比較字串,因此能正確排出漢字的拼音順序,這是單純的預設排序做不到的。這個小技巧在製作人名、地名清單時特別實用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved