2026年5月4日 星期一

關於 String.localeCompare() 的排序結果

 關於 String.localeCompare() 的排序結果

前言

  在之前 再探 Array.toSorted() 會用到 String.localeCompare() 來排序字串,所以就來研究一下預設字串排序是怎麼排的,在此把學習的過程做個紀錄。


內容

  範例如下

let ar = ["BB", "b", 'c' , "a" , "B123",'1'];
//
console.log( 'a'.localeCompare( '1') );//1
console.log( 'a'.localeCompare( 'a') );//0
console.log( 'a'.localeCompare( 'b') );//-1
//
console.log( ar.toSorted( (a , b) => a.toLowerCase().localeCompare(b.toLowerCase() ) ) );
//[ '1', 'a', 'b', 'B123', 'BB', 'c' ]


String.localeCompare() 本身需要輸入被比較的字串當引數,並回傳三種結果,1 、0 與 -1 ,這結果機會是專為排序相關方法而設計,接著利用 Array.toSorted() 來觀察排序的結果,排序是按照每個字的 ASCII code來排 ,那結果的 'B123' 比 'c' 還要前方是怎麼回事呢?因為預設的比較方法有做 toLowerCase() 的關係,所以才會發生大小寫按順序,接著看到 'B123' 與 'BB' 怎麼排的,  'B123' 是被排在前方的!所以不是按照字串的長度來排,而是按照第二個字元,由於 'B123'  的第二個字元是數字所以被排在前方。所以 String.localeCompare() 的排序結果是根據第一個字元的 ASCII code 來比較,如果被比較方的 ASCII code 不一樣那就是結果 '1' 或 '-1' ,如果一樣就在比較第二字元的結果,如果還是一樣就繼續比較第三的資源依此類推,如果比較方發現結束字元那就往左,反之,被比較方發現結束字元就等於不用換,回傳 '0'。


參考資料

[ developer.mozilla.org ] Array.prototype.toSorted()

[ developer.mozilla.org ] String.prototype.localeCompare()


相關文章與資料

再探 Array.toSorted()

初探 Array.toSorted()


沒有留言:

張貼留言